from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException
import pandas as pd
import time
import os
import json
import argparse
import re
from datetime import datetime, date
from driver_manager import get_edge_service

# 并发处理相关导入
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor, as_completed
import queue
import threading
import platform
import tempfile

# 产品类别与工作表映射配置
# 程序会自动处理所有工作表，根据此映射关系为每个工作表的产品设置对应的类别路径
# 注意：新模板使用了更清晰的sheet命名，直接对应产品类别
CATEGORY_SHEET_MAPPING = {
    "男士休闲运动鞋": {
        "sheet_name": "男士休闲运动鞋",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士休闲运动鞋",
    },
    "男士商务休闲鞋": {
        "sheet_name": "男士商务休闲鞋",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士商务休闲鞋",
    },
    "男士公路跑步鞋": {
        "sheet_name": "男士公路跑步鞋",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士运动户外鞋/男士跑步鞋/男士公路跑步鞋",
    },
    "男士滑板鞋": {
        "sheet_name": "男士滑板鞋",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士运动户外鞋/男士滑板鞋",
    },
    # 兼容旧格式（如果还有旧的Excel文件）
    "1": {
        "sheet_name": "Sheet1",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士休闲运动鞋",
    },
    "2": {
        "sheet_name": "Sheet2",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士商务休闲鞋",
    },
    "3": {
        "sheet_name": "Sheet3",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士运动户外鞋/男士跑步鞋/男士公路跑步鞋",
    },
    "4": {
        "sheet_name": "Sheet4",
        "category_path": "服装、鞋靴和珠宝饰品/男士时尚/男鞋/男士运动户外鞋/男士滑板鞋",
    },
}

class DailyLimitManager:
    """每日创建数量限制管理器（多进程安全，跨平台）"""

    def __init__(self, daily_limit=2000, stats_file="daily_stats.json"):
        self.daily_limit = self._load_daily_limit_from_file(daily_limit)
        self.stats_file = stats_file
        self.lock_file = stats_file + ".lock"
        self.today = date.today().isoformat()
        self.is_windows = platform.system() == "Windows"

        # 初始化时加载一次统计数据
        self.stats = self.load_stats_with_lock()

    def _load_daily_limit_from_file(self, default_limit=2000, limit_file="limit.txt"):
        """静默从文件中加载每日限制数值"""
        try:
            if os.path.exists(limit_file):
                with open(limit_file, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                    if content:
                        limit = int(content)
                        if limit > 0:
                            return limit
            return default_limit
        except:
            return default_limit

    def _acquire_file_lock(self, timeout=10):
        """获取文件锁（跨平台实现）"""
        try:
            if self.is_windows:
                # Windows 使用文件重命名作为锁机制
                return self._acquire_lock_windows(timeout)
            else:
                # Unix/Linux/macOS 使用 fcntl
                return self._acquire_lock_unix(timeout)
        except Exception as e:
            print(f"⚠️ 获取文件锁失败: {e}")
            return False

    def _acquire_lock_windows(self, timeout):
        """Windows 平台的文件锁实现"""
        import time
        start_time = time.time()

        while time.time() - start_time < timeout:
            try:
                # 尝试创建锁文件
                with open(self.lock_file, 'x') as f:
                    f.write(str(os.getpid()))
                return True
            except FileExistsError:
                # 锁文件已存在，检查是否是僵尸锁
                try:
                    # 检查锁文件的创建时间，如果太老可能是僵尸锁
                    lock_age = time.time() - os.path.getctime(self.lock_file)
                    if lock_age > 30:  # 30秒以上的锁认为是僵尸锁
                        print(f"⚠️ 检测到僵尸锁文件，尝试清理...")
                        os.remove(self.lock_file)
                        continue
                except:
                    pass

                # 等待一下再试
                time.sleep(0.05)  # 减少等待时间，提高响应速度
            except Exception as e:
                print(f"⚠️ Windows 文件锁获取失败: {e}")
                return False

        return False  # 超时不再打印消息，由调用者处理

    def _acquire_lock_unix(self, timeout):
        """Unix/Linux/macOS 平台的文件锁实现"""
        try:
            import fcntl
            # 创建锁文件
            self.lock_fd = open(self.lock_file, 'w')
            fcntl.flock(self.lock_fd.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            return True
        except ImportError:
            print("⚠️ fcntl 模块不可用，使用备用锁机制")
            return self._acquire_lock_windows(timeout)
        except (IOError, OSError):
            # 锁已被占用
            return False
        except Exception as e:
            print(f"⚠️ Unix 文件锁获取失败: {e}")
            return False

    def _release_file_lock(self):
        """释放文件锁（跨平台实现）"""
        try:
            if self.is_windows:
                self._release_lock_windows()
            else:
                self._release_lock_unix()
        except Exception as e:
            print(f"⚠️ 释放文件锁失败: {e}")

    def _release_lock_windows(self):
        """Windows 平台的文件锁释放"""
        try:
            if os.path.exists(self.lock_file):
                os.remove(self.lock_file)
        except Exception as e:
            print(f"⚠️ Windows 文件锁释放失败: {e}")

    def _release_lock_unix(self):
        """Unix/Linux/macOS 平台的文件锁释放"""
        try:
            if hasattr(self, 'lock_fd') and self.lock_fd:
                import fcntl
                fcntl.flock(self.lock_fd.fileno(), fcntl.LOCK_UN)
                self.lock_fd.close()
                self.lock_fd = None
            if os.path.exists(self.lock_file):
                os.remove(self.lock_file)
        except ImportError:
            self._release_lock_windows()
        except Exception as e:
            print(f"⚠️ Unix 文件锁释放失败: {e}")

    def load_stats_with_lock(self, max_retries=3):
        """使用文件锁加载每日统计数据"""
        for retry in range(max_retries):
            try:
                # 确保统计文件存在
                if not os.path.exists(self.stats_file):
                    default_stats = {
                        'date': self.today,
                        'created_count': 0,
                        'failed_count': 0,
                        'total_attempts': 0
                    }
                    if self.save_stats_with_lock(default_stats):
                        return default_stats
                    else:
                        # 如果保存失败，继续重试
                        continue

                # 使用文件锁读取数据
                if self._acquire_file_lock(timeout=5):
                    try:
                        with open(self.stats_file, 'r', encoding='utf-8') as f:
                            stats = json.load(f)

                            # 如果是新的一天，重置计数
                            if stats.get('date') != self.today:
                                print(f"📅 检测到新的一天，重置创建计数")
                                stats = {
                                    'date': self.today,
                                    'created_count': 0,
                                    'failed_count': 0,
                                    'total_attempts': 0
                                }
                                # 立即写入重置后的数据
                                self._release_file_lock()
                                if self.save_stats_with_lock(stats):
                                    return stats
                                else:
                                    continue  # 保存失败，重试

                            return stats
                    finally:
                        self._release_file_lock()
                else:
                    # 锁获取失败，重试
                    if retry < max_retries - 1:
                        import time
                        time.sleep(0.1 * (retry + 1))  # 递增等待时间
                        continue

            except Exception as e:
                if retry < max_retries - 1:
                    import time
                    time.sleep(0.1 * (retry + 1))
                    continue
                else:
                    print(f"⚠️ 加载统计数据失败: {e}")

        # 所有重试都失败，返回默认数据
        return {
            'date': self.today,
            'created_count': 0,
            'failed_count': 0,
            'total_attempts': 0
        }

    def save_stats_with_lock(self, stats, max_retries=3):
        """使用文件锁保存统计数据"""
        for retry in range(max_retries):
            try:
                if self._acquire_file_lock(timeout=5):
                    try:
                        with open(self.stats_file, 'w', encoding='utf-8') as f:
                            json.dump(stats, f, ensure_ascii=False, indent=2)
                            f.flush()
                            if not self.is_windows:
                                os.fsync(f.fileno())  # 强制写入磁盘（Windows 可能不支持）
                        return True
                    finally:
                        self._release_file_lock()
                else:
                    # 锁获取失败，重试
                    if retry < max_retries - 1:
                        import time
                        time.sleep(0.1 * (retry + 1))  # 递增等待时间
                        continue

            except Exception as e:
                if retry < max_retries - 1:
                    import time
                    time.sleep(0.1 * (retry + 1))
                    continue
                else:
                    print(f"⚠️ 保存统计数据失败: {e}")

        return False

    def refresh_stats(self):
        """刷新统计数据（从文件重新加载）"""
        self.stats = self.load_stats_with_lock()

    def can_create_more(self):
        """检查是否还能创建更多产品（实时检查）"""
        # 每次检查前都刷新数据，确保获取最新状态
        self.refresh_stats()
        return self.stats['created_count'] < self.daily_limit

    def get_remaining_quota(self):
        """获取剩余配额（实时检查）"""
        self.refresh_stats()
        return max(0, self.daily_limit - self.stats['created_count'])

    def record_success(self):
        """记录创建成功（多进程安全）"""
        try:
            # 重新加载最新数据
            current_stats = self.load_stats_with_lock()

            # 检查是否已达到限制
            if current_stats['created_count'] >= self.daily_limit:
                print(f"🚫 已达到每日创建限制 {self.daily_limit}，无法继续创建")
                return False

            # 更新计数
            current_stats['created_count'] += 1
            current_stats['total_attempts'] += 1

            # 保存更新后的数据
            if self.save_stats_with_lock(current_stats):
                self.stats = current_stats  # 更新本地缓存

                remaining = self.get_remaining_quota()
                print(f"✅ 创建成功计数更新: {current_stats['created_count']}/{self.daily_limit}")
                print(f"📊 今日剩余配额: {remaining}")

                if remaining <= 10:
                    print(f"⚠️ 警告: 今日剩余配额不足10个!")

                if remaining == 0:
                    print(f"🚫 今日创建配额已用完!")

                return remaining > 0
            else:
                print(f"⚠️ 保存统计数据失败，无法更新计数")
                return False

        except Exception as e:
            print(f"⚠️ 记录创建成功失败: {e}")
            return False

    def record_failure(self):
        """记录创建失败（多进程安全）"""
        try:
            # 重新加载最新数据
            current_stats = self.load_stats_with_lock()

            # 更新计数
            current_stats['failed_count'] += 1
            current_stats['total_attempts'] += 1

            # 保存更新后的数据
            if self.save_stats_with_lock(current_stats):
                self.stats = current_stats  # 更新本地缓存
                print(f"❌ 创建失败计数更新: {current_stats['failed_count']}")
            else:
                print(f"⚠️ 保存失败统计数据失败")

        except Exception as e:
            print(f"⚠️ 记录创建失败失败: {e}")

    def get_daily_summary(self):
        """获取今日统计摘要"""
        return {
            'date': self.stats['date'],
            'created': self.stats['created_count'],
            'failed': self.stats['failed_count'],
            'total_attempts': self.stats['total_attempts'],
            'remaining': self.get_remaining_quota(),
            'success_rate': (self.stats['created_count'] / max(1, self.stats['total_attempts'])) * 100
        }

    def print_daily_summary(self):
        """打印今日统计摘要"""
        summary = self.get_daily_summary()
        print(f"\n📊 今日创建统计 ({summary['date']}):")
        print(f"   ✅ 创建成功: {summary['created']}")
        print(f"   ❌ 创建失败: {summary['failed']}")
        print(f"   📈 总尝试数: {summary['total_attempts']}")
        print(f"   📋 剩余配额: {summary['remaining']}")
        print(f"   🎯 成功率: {summary['success_rate']:.1f}%")

        if summary['remaining'] == 0:
            print(f"🚫 今日创建配额已用完!")
        elif summary['remaining'] <= 10:
            print(f"⚠️ 今日剩余配额不足10个，请注意!")

class ProductData:
    """产品数据类 - 支持读取所有工作表"""

    def __init__(self, excel_file="production2.xlsx", sheet_name=None):
        self.excel_file = excel_file
        self.sheet_name = sheet_name  # 如果为 None，则读取所有工作表
        self.products = []  # 单工作表模式下的产品列表
        self.products_by_sheet = {}  # 多工作表模式下按 sheet_name 分组的产品字典
        self.df = None

    def load_excel(self):
        """从Excel文件加载产品数据
        
        Returns:
            bool: 加载是否成功
        """
        try:
            print(f"📖 正在读取Excel文件: {self.excel_file}")

            read_kwargs = {"engine": "openpyxl"}
            if self.sheet_name:
                # 单工作表模式
                read_kwargs["sheet_name"] = self.sheet_name
                print(f"🗂️ 读取指定工作表: {self.sheet_name}")
                self.df = pd.read_excel(self.excel_file, **read_kwargs)
                print(f"📋 工作表 '{self.sheet_name}' 包含 {len(self.df)} 行数据")
                return self._parse_single_sheet(self.df)
            else:
                # 多工作表模式 - 读取所有工作表
                print("🗂️ 读取所有工作表...")
                read_kwargs["sheet_name"] = None  # 读取所有工作表
                all_sheets = pd.read_excel(self.excel_file, **read_kwargs)
                
                if not isinstance(all_sheets, dict):
                    print("⚠️ Excel 文件只包含单个工作表")
                    self.df = all_sheets
                    return self._parse_single_sheet(all_sheets)
                
                # 处理多个工作表
                return self._parse_all_sheets(all_sheets)

            # 检查数据是否足够（至少需要1行数据）
            if len(self.df) < 1:
                print("❌ Excel文件没有数据")
                return False
        except Exception as e:
            print(f"❌ 读取Excel文件失败: {e}")
            return False
    
    def _parse_single_sheet(self, df):
        """解析单个工作表的数据
        
        Args:
            df: pandas DataFrame
            
        Returns:
            bool: 解析是否成功
        """
        self.products = []
        
        # 打印Excel中的所有列名，用于调试
        print("\n" + "="*60)
        print("🔍 Excel文件中的所有列名:")
        print("="*60)
        for i, col in enumerate(df.columns, 1):
            print(f"   {i:2d}. '{col}'")
        print("="*60 + "\n")
        
        # 解析产品数据
        for index, row in df.iterrows():
            product = self._parse_product_row(row, index)
            if product:
                self.products.append(product)
        
        print(f"✅ 成功加载 {len(self.products)} 个产品")
        return True
    
    def _parse_all_sheets(self, all_sheets):
        """解析所有工作表的数据
        
        Args:
            all_sheets: dict of pandas DataFrames
            
        Returns:
            bool: 解析是否成功
        """
        self.products_by_sheet = {}
        total_products = 0
        
        print(f"📊 找到 {len(all_sheets)} 个工作表")
        
        for sheet_name, df in all_sheets.items():
            print(f"\n🗂️ 正在解析工作表: {sheet_name}")
            print(f"   包含 {len(df)} 行数据")
            
            # 打印该工作表的所有列名
            print("\n" + "="*60)
            print(f"🔍 工作表 '{sheet_name}' 的所有列名:")
            print("="*60)
            for i, col in enumerate(df.columns, 1):
                print(f"   {i:2d}. '{col}'")
            print("="*60 + "\n")
            
            sheet_products = []
            for index, row in df.iterrows():
                product = self._parse_product_row(row, index)
                if product:
                    sheet_products.append(product)
            
            if sheet_products:
                self.products_by_sheet[sheet_name] = sheet_products
                total_products += len(sheet_products)
                print(f"   ✅ 成功加载 {len(sheet_products)} 个产品")
            else:
                print(f"   ⚠️ 该工作表没有有效产品数据")
        
        print(f"\n✅ 总共成功加载 {total_products} 个产品，来自 {len(self.products_by_sheet)} 个工作表")
        return len(self.products_by_sheet) > 0
    
    def _get_column_value(self, row, possible_names):
        """
        尝试从多个可能的列名中获取值
        
        Args:
            row: pandas Series
            possible_names: 可能的列名列表
            
        Returns:
            str: 找到的值，如果都找不到则返回空字符串
        """
        for name in possible_names:
            if name in row.index and pd.notna(row.get(name)):
                value = str(row[name]).strip()
                if value:  # 确保不是空字符串
                    return value
        return ""
    
    def _parse_product_row(self, row, index):
        """解析单行产品数据
        
        Args:
            row: pandas Series
            index: 行索引
            
        Returns:
            dict: 产品数据字典，解析失败返回 None
        """
        try:
            # 处理图片文件夹
            if pd.notna(row.get('图片文件夹')):
                image_folder = str(row['图片文件夹']).strip()
            else:
                image_folder = None

            # 处理价格数据
            price_raw = row.get('供货价')
            if pd.isna(price_raw) or price_raw == '':
                price = 0
            else:
                price = float(str(price_raw).strip())

            # 处理建议售价数据
            sale_price_raw = row.get('建议售价')
            if pd.isna(sale_price_raw) or sale_price_raw == '':
                sale_price = 0
            else:
                sale_price = float(str(sale_price_raw).strip())

            # 处理颜色 - 支持多种可能的列名格式（包括中文冒号和英文冒号）
            color_value = self._get_column_value(row, [
                '规格1：颜色', '规格1: 颜色', '规格1:颜色', '规格1_颜色', '颜色', 'Color', 'color'
            ])
            
            # 处理尺码 - 支持多种可能的列名格式（包括中文冒号和英文冒号）
            size_value = self._get_column_value(row, [
                '规格2：尺码', '规格2: 尺码', '规格2:尺码', '规格2_尺码', '尺码', 'Size', 'size'
            ])

            product = {
                "产品标题": str(row['产品标题']).strip() if pd.notna(row.get('产品标题')) else "",
                "主货号": str(row['主货号']).strip() if pd.notna(row.get('主货号')) else "",
                "产品类别": str(row['产品类别']).strip() if pd.notna(row.get('产品类别')) else "",
                "规格1_颜色": color_value,
                "规格2_尺码": size_value,
                "供货价": price,
                "建议售价": sale_price,
                "图片文件夹": image_folder,
                "鞋面材料": str(row['鞋面材料']).strip() if pd.notna(row.get('鞋面材料')) else "",
                "鞋底材料": str(row['鞋底材料']).strip() if pd.notna(row.get('鞋底材料')) else "",
                "内里材料": str(row['内里材料']).strip() if pd.notna(row.get('内里材料')) else "",
                "闭合方式": str(row['闭合方式']).strip() if pd.notna(row.get('闭合方式')) else "",
                "鞋头": str(row['鞋头']).strip() if pd.notna(row.get('鞋头')) else "",
                "适用人群": str(row['适用人群']).strip() if pd.notna(row.get('适用人群')) else "",
                "图案": str(row['图案']).strip() if pd.notna(row.get('图案')) else "",
                "场景": str(row['场景']).strip() if pd.notna(row.get('场景')) else "",
                "风格": str(row['风格']).strip() if pd.notna(row.get('风格')) else "",
                "季节": str(row['季节']).strip() if pd.notna(row.get('季节')) else "",
                "帮高筒高": str(row['帮高筒高']).strip() if pd.notna(row.get('帮高筒高')) else "",
                "鞋垫材料": str(row['鞋垫材料']).strip() if pd.notna(row.get('鞋垫材料')) else "",
                "护理说明": str(row['护理说明']).strip() if pd.notna(row.get('护理说明')) else "",
                "印花类型": str(row['印花类型']).strip() if pd.notna(row.get('印花类型')) else "",
                "产地": str(row['产地']).strip() if pd.notna(row.get('产地')) else "",
                "SKU分类": str(row['SKU分类']).strip() if pd.notna(row.get('SKU分类')) else "",
                "敏感属性": str(row['敏感属性']).strip() if pd.notna(row.get('敏感属性')) else "",
                "外包装形状": str(row['外包装形状']).strip() if pd.notna(row.get('外包装形状')) else "",
                "外包装类型": str(row['外包装类型']).strip() if pd.notna(row.get('外包装类型')) else "",
                "货源信息": str(row['货源信息']).strip() if pd.notna(row.get('货源信息')) else "",
                "商家信息": str(row['商家信息']).strip() if pd.notna(row.get('商家信息')) else "",
                "商家信息2": str(row['商家信息2']).strip() if pd.notna(row.get('商家信息2')) else "",  # 新模板新增字段
            }
            return product
        except Exception as e:
            print(f"⚠️ 解析第 {index + 2} 行数据出错: {e}")
            print(f"   可用的列: {list(row.index)}")
            return None

    def get_products(self):
        """获取产品列表"""
        return self.products
    
    def get_product_by_id(self, product_id):
        """根据产品编号获取产品"""
        for product in self.products:
            if product['产品编号'] == product_id:
                return product
        return None
    
    def display_products(self):
        """显示所有产品信息"""
        if not self.products:
            print("❌ 没有产品数据")
            return

        print("\n📋 产品列表:")
        print("-" * 120)
        for i, product in enumerate(self.products, 1):
            print(f"{i}. {product['产品标题']}")
            print(f"   主货号: {product.get('主货号', '')}")
            print(f"   产品类别: {product['产品类别']}")
            print(f"   颜色: {product['规格1_颜色']}, 尺码: {product['规格2_尺码']}")
            print(f"   供货价: {product['供货价']}, 建议售价: {product['建议售价']}")
            print(f"   鞋面材料: {product['鞋面材料']}, 鞋底材料: {product['鞋底材料']}, 内里材料: {product['内里材料']}")
            print(f"   闭合方式: {product['闭合方式']}, 鞋头: {product['鞋头']}, 适用人群: {product['适用人群']}")
            print(f"   图案: {product['图案']}, 场景: {product['场景']}, 风格: {product['风格']}, 季节: {product['季节']}")
            print(f"   帮高筒高: {product['帮高筒高']}, 鞋垫材料: {product['鞋垫材料']}")
            print(f"   护理说明: {product['护理说明']}, 印花类型: {product['印花类型']}, 产地: {product['产地']}")
            print(f"   SKU分类: {product['SKU分类']}, 敏感属性: {product['敏感属性']}")
            print(f"   外包装形状: {product['外包装形状']}, 外包装类型: {product['外包装类型']}")
            print(f"   货源信息: {product['货源信息']}, 商家信息: {product['商家信息']}")
            print("-" * 120)

class ERPAutomation:
    """ERP自动化操作类"""

    def __init__(self, daily_limit=2000, category_path=None, size_template_file="标准尺码模版.xlsx"):
        self.driver = None
        self.product_data = None
        self.daily_limit_manager = DailyLimitManager(daily_limit)

        # 产品类别配置（现在支持动态设置）
        self.default_category_path = category_path  # 如果提供，则使用指定的类别路径
        self.current_category_path = category_path  # 当前处理产品的类别路径
        if category_path:
            print(f"🗂️ 使用指定的产品类别路径: {category_path}")

        # 从Excel加载尺码模版数据
        self.size_template_file = size_template_file
        size_data_loaded = self.load_size_data_from_excel(size_template_file)
        
        if size_data_loaded:
            # 成功从Excel加载数据
            self.women_size_data = size_data_loaded  # 女鞋使用标准模版数据
            self.men_size_data = size_data_loaded    # 男鞋也使用标准模版数据
            print(f"✅ 已从 '{size_template_file}' 加载尺码数据（{len(size_data_loaded)}个尺码）")
        else:
            # 如果Excel加载失败，使用备用的硬编码数据
            print("⚠️ Excel加载失败，使用备用硬编码数据")
            # 女鞋尺码模版数据（备用数据）
            self.women_size_data = {
                "28": {"length": 21, "width": 18, "height": 11, "weight": 290},
                "29": {"length": 21.5, "width": 18, "height": 11, "weight": 300},
                "30": {"length": 22, "width": 18, "height": 11, "weight": 310},
                "31": {"length": 22.5, "width": 18, "height": 11, "weight": 320},
                "32": {"length": 23, "width": 18, "height": 11, "weight": 330},
                "33": {"length": 23.5, "width": 18, "height": 11, "weight": 340},
                "34": {"length": 24, "width": 18, "height": 11, "weight": 350},
                "35": {"length": 24.5, "width": 18, "height": 11, "weight": 360},
                "36": {"length": 25, "width": 18, "height": 11, "weight": 370},
                "37": {"length": 25.5, "width": 18, "height": 11, "weight": 380},
                "38": {"length": 26, "width": 18, "height": 11, "weight": 390},
                "39": {"length": 26.5, "width": 18, "height": 11, "weight": 400},
                "40": {"length": 27, "width": 18, "height": 11, "weight": 410},
                "41": {"length": 27.5, "width": 18, "height": 11, "weight": 420},
                "42": {"length": 28, "width": 18, "height": 11, "weight": 430},
                "43": {"length": 28.5, "width": 18, "height": 11, "weight": 440},
                "44": {"length": 29, "width": 18, "height": 11, "weight": 450},
                "45": {"length": 29.5, "width": 18, "height": 11, "weight": 460},
                "46": {"length": 30, "width": 18, "height": 11, "weight": 470},
                "47": {"length": 30.5, "width": 18, "height": 11, "weight": 480},
                "48": {"length": 31, "width": 18, "height": 11, "weight": 490},
            }

            # 男鞋尺码模版数据（备用数据）
            self.men_size_data = {
                "28": {"length": 22, "width": 18, "height": 11, "weight": 300},
                "29": {"length": 22.5, "width": 18, "height": 11, "weight": 310},
                "30": {"length": 23, "width": 18, "height": 11, "weight": 320},
                "31": {"length": 23.5, "width": 18, "height": 11, "weight": 330},
                "32": {"length": 24, "width": 18, "height": 11, "weight": 340},
                "33": {"length": 24.5, "width": 18, "height": 11, "weight": 350},
                "34": {"length": 25, "width": 18, "height": 11, "weight": 360},
                "35": {"length": 25.5, "width": 18, "height": 11, "weight": 370},
                "36": {"length": 26, "width": 18, "height": 11, "weight": 380},
                "37": {"length": 26.5, "width": 18, "height": 11, "weight": 390},
                "38": {"length": 27, "width": 18, "height": 11, "weight": 400},
                "39": {"length": 27.5, "width": 18, "height": 11, "weight": 410},
                "40": {"length": 28, "width": 18, "height": 11, "weight": 420},
                "41": {"length": 28.5, "width": 18, "height": 11, "weight": 430},
                "42": {"length": 29, "width": 18, "height": 11, "weight": 440},
                "43": {"length": 29.5, "width": 18, "height": 11, "weight": 450},
                "44": {"length": 30, "width": 18, "height": 11, "weight": 460},
                "45": {"length": 30.5, "width": 18, "height": 11, "weight": 470},
                "46": {"length": 31, "width": 18, "height": 11, "weight": 480},
                "47": {"length": 31.5, "width": 18, "height": 11, "weight": 490},
                "48": {"length": 32, "width": 18, "height": 11, "weight": 500},
                "49": {"length": 32.5, "width": 18, "height": 11, "weight": 510},
                "50": {"length": 33, "width": 18, "height": 11, "weight": 520},
            }

        # 当前使用的尺码数据（将根据产品尺码范围动态设置）
        self.size_data = self.women_size_data  # 默认使用女鞋数据
        self.current_shoe_type = "女鞋"  # 记录当前判断的鞋子类型
        self.shoe_category_type = None  # 记录具体的鞋子类别类型（用于选择尺码表模板）
        
        # 定义产品类别到尺码表模板的映射关系
        self.category_to_size_chart = {
            "男士休闲运动鞋": "男士运动休闲鞋",
            "男士运动休闲鞋": "男士运动休闲鞋",
            "男士商务休闲鞋": "男士商务休闲鞋",
            "男士公路跑步鞋": "男士公路跑步鞋",
            "男士滑板鞋": "男士滑板鞋",
        }

    def load_size_data_from_excel(self, excel_file):
        """从Excel文件加载尺码数据
        
        Args:
            excel_file: Excel文件路径
            
        Returns:
            dict: 尺码数据字典，格式为 {"尺码": {"length": 长, "width": 宽, "height": 高, "weight": 重量}}
                  如果加载失败返回None
        """
        try:
            import pandas as pd
            import os
            
            print(f"📚 正在从 '{excel_file}' 加载尺码模版数据...")
            
            # 检查文件是否存在
            if not os.path.exists(excel_file):
                print(f"❌ 文件不存在: {excel_file}")
                return None
            
            # 读取Excel文件（不设置header，因为前几行是标题）
            df = pd.read_excel(excel_file, header=None)
            
            # 检查数据结构
            if df.shape[0] < 4 or df.shape[1] < 7:
                print(f"❌ Excel文件格式不正确，行数或列数不足")
                return None
            
            # Excel结构：
            # 第1行(索引0)：空行
            # 第2行(索引1)：标题行 - 尺码、敏感属性、体积、重量
            # 第3行(索引2)：子标题行 - 最长边、次长边、最短边
            # 第4行开始(索引3-)：数据行
            
            size_data = {}
            
            # 从第4行开始读取数据（索引3开始）
            for idx in range(3, len(df)):
                try:
                    row = df.iloc[idx]
                    
                    # 列结构：
                    # 列1: 尺码
                    # 列2: 敏感属性
                    # 列3: 最长边（长）
                    # 列4: 次长边（宽）
                    # 列5: 最短边（高）
                    # 列6: 重量
                    
                    size = str(int(row[1])) if pd.notna(row[1]) else None  # 尺码
                    length = float(row[3]) if pd.notna(row[3]) else None   # 最长边
                    width = float(row[4]) if pd.notna(row[4]) else None    # 次长边
                    height = float(row[5]) if pd.notna(row[5]) else None   # 最短边
                    weight = int(row[6]) if pd.notna(row[6]) else None     # 重量
                    
                    # 检查必要字段是否存在
                    if size and length is not None and width is not None and height is not None and weight is not None:
                        size_data[size] = {
                            "length": length,
                            "width": width,
                            "height": height,
                            "weight": weight
                        }
                    
                except Exception as e:
                    # 某行数据解析失败，继续处理下一行
                    continue
            
            if size_data:
                print(f"✅ 成功加载 {len(size_data)} 个尺码的数据")
                print(f"   尺码范围: {min(size_data.keys(), key=lambda x: int(x))} - {max(size_data.keys(), key=lambda x: int(x))}")
                return size_data
            else:
                print(f"❌ 未能从Excel中解析出有效数据")
                return None
                
        except Exception as e:
            print(f"❌ 加载尺码模版数据失败: {e}")
            import traceback
            traceback.print_exc()
            return None

    def determine_shoe_type_and_set_size_data(self, size_value, product_data=None):
        """根据尺码范围判断男鞋女鞋并设置对应的尺码数据，同时根据产品类别确定具体子类型"""
        try:
            print(f"🔍 分析尺码范围来判断鞋子类型: {size_value}")
            
            # 1. 首先从产品类别中提取具体的鞋子类型
            if product_data:
                product_category = product_data.get('产品类别', '')
                if product_category:
                    print(f"📦 产品类别: {product_category}")
                    # 提取最后一个"/"后面的字段
                    category_parts = product_category.split('/')
                    if category_parts:
                        last_category = category_parts[-1].strip()
                        print(f"🔍 提取的具体类别: {last_category}")
                        
                        # 查找映射的尺码表模板类型
                        if last_category in self.category_to_size_chart:
                            self.shoe_category_type = self.category_to_size_chart[last_category]
                            print(f"✅ 匹配到尺码表模板类型: {self.shoe_category_type}")
                        else:
                            print(f"⚠️ 未找到'{last_category}'对应的尺码表模板，将使用默认匹配")
                            self.shoe_category_type = None

            # 解析尺码范围
            size_list = self.parse_size_range(size_value)
            numeric_sizes = [int(size) for size in size_list if size.isdigit()]

            if not numeric_sizes:
                print("⚠️ 没有有效的数字尺码，使用默认女鞋模版")
                self.size_data = self.women_size_data
                self.current_shoe_type = "女鞋"
                return

            min_size = min(numeric_sizes)
            max_size = max(numeric_sizes)
            avg_size = sum(numeric_sizes) / len(numeric_sizes)

            print(f"   尺码范围: {min_size}-{max_size}, 平均尺码: {avg_size:.1f}")

            # 判断逻辑（基于标准模版分析）：
            # 1. 如果包含49码或50码，肯定是男鞋（女鞋模版没有这些尺码）
            # 2. 如果最小尺码 >= 40，很可能是男鞋
            # 3. 如果最大尺码 <= 36，很可能是女鞋
            # 4. 如果平均尺码 >= 41，倾向于男鞋
            # 5. 如果平均尺码 <= 35，倾向于女鞋
            # 6. 中间范围根据尺码分布和重心判断

            is_mens_shoe = False
            reason = ""

            if 49 in numeric_sizes or 50 in numeric_sizes:
                is_mens_shoe = True
                reason = f"包含49码或50码（女鞋模版没有这些尺码）"
            elif min_size >= 40:
                is_mens_shoe = True
                reason = f"最小尺码{min_size} >= 40"
            elif max_size <= 36:
                is_mens_shoe = False
                reason = f"最大尺码{max_size} <= 36"
            elif avg_size >= 41:
                is_mens_shoe = True
                reason = f"平均尺码{avg_size:.1f} >= 41"
            elif avg_size <= 35:
                is_mens_shoe = False
                reason = f"平均尺码{avg_size:.1f} <= 35"
            else:
                # 中间范围（36-40），根据尺码分布和重心判断
                large_sizes = [s for s in numeric_sizes if s >= 40]
                small_sizes = [s for s in numeric_sizes if s <= 37]
                medium_sizes = [s for s in numeric_sizes if 38 <= s <= 39]

                # 计算尺码重心（大尺码权重更高）
                weighted_sum = sum(s * (1.2 if s >= 40 else 1.0) for s in numeric_sizes)
                weighted_avg = weighted_sum / len(numeric_sizes)

                if len(large_sizes) > len(small_sizes) + 1:  # 大尺码明显更多
                    is_mens_shoe = True
                    reason = f"大尺码({len(large_sizes)}个) > 小尺码({len(small_sizes)}个)+1"
                elif weighted_avg >= 38.5:  # 加权平均偏向大尺码
                    is_mens_shoe = True
                    reason = f"加权平均尺码{weighted_avg:.1f} >= 38.5"
                else:
                    is_mens_shoe = False
                    reason = f"小尺码({len(small_sizes)}个) + 中等尺码({len(medium_sizes)}个) 占优势"

            # 设置对应的尺码数据
            if is_mens_shoe:
                self.size_data = self.men_size_data
                self.current_shoe_type = "男鞋"
                print(f"   🚹 判断为男鞋 - {reason}")
                print(f"   📊 使用男鞋模版数据（{len(self.men_size_data)}个尺码）")
            else:
                self.size_data = self.women_size_data
                self.current_shoe_type = "女鞋"
                print(f"   🚺 判断为女鞋 - {reason}")
                print(f"   📊 使用女鞋模版数据（{len(self.women_size_data)}个尺码）")

            # 检查尺码覆盖情况
            available_sizes = set(self.size_data.keys())
            required_sizes = set(str(s) for s in numeric_sizes)
            missing_sizes = required_sizes - available_sizes

            if missing_sizes:
                print(f"   ⚠️ 模版中缺少的尺码: {sorted(missing_sizes)}")
                print(f"   💡 这些尺码将无法自动填写长宽高重量数据")
            else:
                print(f"   ✅ 模版完全覆盖所需尺码")

        except Exception as e:
            print(f"❌ 判断鞋子类型失败: {e}")
            # 出错时使用默认女鞋数据
            self.size_data = self.women_size_data
            self.current_shoe_type = "女鞋"

    def setup_browser(self):
        """设置浏览器"""
        try:
            # Edge 浏览器配置
            options = Options()
            # options.add_argument('--headless')  # 可选：无头运行
            options.add_argument('--disable-gpu')
            options.add_argument('--no-sandbox')
            options.add_argument('--disable-dev-shm-usage')

            # 添加全屏启动参数
            options.add_argument('--start-maximized')  # 启动时最大化窗口
            options.add_argument('--window-size=1920,1080')  # 设置默认窗口大小

            # 使用跨平台驱动管理器
            service = get_edge_service("msedgedriver1")

            # 初始化 Edge 浏览器
            self.driver = webdriver.Edge(service=service, options=options)

            # 确保浏览器全屏
            try:
                self.driver.maximize_window()  # 最大化窗口

                # 获取窗口信息用于验证
                window_size = self.driver.get_window_size()
                print(f"🖥️ 浏览器已设置为全屏模式 ({window_size['width']}x{window_size['height']})")

            except Exception as e:
                print(f"⚠️ 设置全屏模式时出现警告: {e}")
                # 即使出现警告，也尝试继续运行

            print("✅ 浏览器初始化成功")
            return True

        except Exception as e:
            print(f"❌ 浏览器初始化失败: {e}")
            return False
    
    def login_erp(self, username="15570366559", password="Yanjun6559."):
        """登录ERP系统"""
        try:
            print("🔐 正在访问ERP登录页面...")
            self.driver.get("https://erp.91miaoshou.com/?redirect=%2Fpddkj%2Fcollect_box%2Fitems")

            # 等待页面加载
            time.sleep(2)  # 优化：5s -> 2s

            # 查找手机号输入框（登录用的第一个mobile输入框）
            print("📝 正在填写登录信息...")
            mobile_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='mobile'].account-input"))
            )
            mobile_input.clear()
            mobile_input.send_keys(username)

            # 查找密码输入框（登录用的密码输入框）
            password_input = self.driver.find_element(By.CSS_SELECTOR, "input[name='password'].password-input")
            password_input.clear()
            password_input.send_keys(password)

            # 点击登录按钮
            print("🔑 正在登录...")
            login_button = self.driver.find_element(By.CSS_SELECTOR, "button.login-button")
            login_button.click()

            # 等待登录完成 - 检查URL变化或页面元素
            print("⏳ 等待登录完成...")
            try:
                # 等待URL包含目标页面或者页面标题变化
                WebDriverWait(self.driver, 15).until(
                    lambda driver: "pddkj/collect_box/items" in driver.current_url or
                                 "登录" not in driver.title
                )

                # 额外等待页面完全加载
                time.sleep(1)  # 优化：3s -> 1s

                print(f"📄 当前页面: {self.driver.current_url}")
                print("✅ 登录成功")
                return True

            except TimeoutException:
                print(f"⚠️ 登录可能需要验证码或其他操作")
                print(f"📄 当前页面: {self.driver.current_url}")
                print(f"📄 页面标题: {self.driver.title}")

                # 检查是否需要验证码
                try:
                    captcha_elements = self.driver.find_elements(By.CLASS_NAME, "login-verify-form-input")
                    if captcha_elements:
                        print("🔐 检测到验证码，请手动完成验证...")
                        input("完成验证后按回车键继续...")
                        return True
                except:
                    pass

                return False

        except TimeoutException:
            print("❌ 登录超时，请检查网络连接或登录信息")
            print(f"📄 当前页面: {self.driver.current_url}")
            return False
        except Exception as e:
            print(f"❌ 登录失败: {e}")
            print(f"📄 当前页面: {self.driver.current_url}")
            return False
    
    def load_product_data(self, excel_file="production2.xlsx", sheet_name=None):
        """加载产品数据
        
        Args:
            excel_file: Excel文件路径
            sheet_name: 工作表名称，如果为None则读取所有工作表
            
        Returns:
            bool: 是否成功加载
        """
        try:
            if sheet_name:
                print(f"📥 正在加载产品数据 - 工作表: {sheet_name}")
            else:
                print(f"📥 正在加载所有工作表的产品数据...")
            
            self.product_data = ProductData(excel_file, sheet_name=sheet_name)
            loaded = self.product_data.load_excel()
            
            if loaded:
                if sheet_name:
                    print(f"✅ 成功加载 {len(self.product_data.products)} 个产品")
                else:
                    total = sum(len(products) for products in self.product_data.products_by_sheet.values())
                    print(f"✅ 成功加载 {total} 个产品，来自 {len(self.product_data.products_by_sheet)} 个工作表")
            return loaded
        except Exception as e:
            print(f"❌ 加载产品数据失败: {e}")
            return False
    
    def handle_popups(self):
        """彻底处理登录后的弹窗"""
        try:
            print("🔍 彻底处理登录后弹窗...")

            popup_count = 0
            max_attempts = 5  # 增加到5轮

            for attempt in range(max_attempts):
                print(f"   🔄 第{attempt + 1}轮弹窗检查...")
                round_closed = 0

                # 扩展的弹窗关闭选择器
                close_selectors = [
                    ".jx-dialog__close",           # jx对话框关闭按钮
                    ".jx-modal-close",             # jx模态框关闭按钮
                    ".ant-modal-close",            # ant模态框关闭按钮
                    ".ant-modal-close-x",          # ant模态框关闭X
                    ".modal-close",                # 通用模态框关闭
                    ".close",                      # 通用关闭按钮
                    "[aria-label='Close']",         # 中文关闭标签
                    "[aria-label='close']",        # 英文关闭标签
                    "[aria-label='close']",        # 小写关闭标签
                    "button[class*='close']",      # 包含close的按钮
                    "i[class*='close']",           # 关闭图标
                    ".fa-times",                   # FontAwesome关闭图标
                    ".fa-close",                   # FontAwesome关闭图标
                    "//button[contains(@class, 'close')]",
                    "//span[contains(@class, 'close')]",
                    "//i[contains(@class, 'close')]"
                ]

                for selector in close_selectors:
                    try:
                        if selector.startswith("//"):
                            close_buttons = self.driver.find_elements(By.XPATH, selector)
                        else:
                            close_buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)

                        for btn in close_buttons:
                            if btn.is_displayed():
                                try:
                                    self.driver.execute_script("arguments[0].click();", btn)
                                    round_closed += 1
                                    popup_count += 1
                                    print(f"   ✅ 关闭弹窗 {popup_count} (选择器: {selector[:30]}...)")
                                    time.sleep(1)
                                except:
                                    pass
                    except:
                        continue

                if not round_closed:
                    break

                time.sleep(1)

            # 按ESC键作为最后的保险
            try:
                from selenium.webdriver.common.keys import Keys
                self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                time.sleep(1)
                print("   ✅ 按ESC键关闭可能的弹窗")
            except:
                pass

            if popup_count > 0:
                print(f"✅ 总共关闭了 {popup_count} 个弹窗")
                time.sleep(2)  # 最终等待
            else:
                print("ℹ️ 未检测到弹窗")

            # 新增：处理 jx-tour 引导提示
            print("\n🔍 检查并处理 jx-tour 引导提示...")
            tour_success = self.handle_tour_popup()

            if tour_success:
                print("✅ tour引导提示处理完成")
            else:
                print("⚠️ tour引导提示处理失败，但不影响主流程")

            return True

        except Exception as e:
            print(f"❌ 处理弹窗失败: {e}")
            return False

    def handle_tour_popup(self):
        """
        处理 jx-tour 引导提示弹窗

        在关闭常规弹窗后，可能会出现引导提示（tour），需要点击其关闭按钮
        来关闭hover提示，这样才能正常操作页面上的其他按钮

        Returns:
            是否成功处理tour提示（如果没有tour提示也返回True）
        """
        try:
            print("🔍 检查是否存在 jx-tour 引导提示...")

            # 1. 查找所有tour容器
            tour_containers = []
            tour_selectors = [
                ".jx-tour",
                "div.jx-tour",
                "[class*='jx-tour']"
            ]

            for selector in tour_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for elem in elements:
                        if elem.is_displayed():
                            tour_containers.append(elem)
                            print(f"   ✅ 找到tour容器: {selector}")
                except Exception as e:
                    print(f"   ⚠️ 选择器 {selector} 失败: {e}")
                    continue

            if not tour_containers:
                print("ℹ️ 未发现 jx-tour 引导提示，跳过处理")
                return True

            print(f"📋 发现 {len(tour_containers)} 个tour提示，开始处理...")

            # 2. 处理每个tour容器
            success_count = 0
            for i, container in enumerate(tour_containers):
                print(f"\n🔍 处理第 {i+1} 个tour提示:")

                try:
                    # 显示容器信息
                    container_class = container.get_attribute("class") or ""
                    container_id = container.get_attribute("id") or ""
                    print(f"   📋 容器信息: id='{container_id}' class='{container_class[:50]}'")

                    # 查找关闭按钮
                    close_button = self._find_tour_close_button(container)

                    if close_button:
                        button_text = close_button.text.strip() if close_button.text else ""
                        button_class = close_button.get_attribute("class") or ""
                        print(f"   ✅ 找到关闭按钮: '{button_text}' (class: {button_class[:30]})")

                        # 点击关闭按钮
                        try:
                            self.driver.execute_script("arguments[0].click();", close_button)
                            print(f"   ✅ 成功点击第 {i+1} 个tour关闭按钮")
                            success_count += 1
                            time.sleep(1)  # 等待动画完成
                        except Exception as e:
                            print(f"   ❌ 点击第 {i+1} 个tour关闭按钮失败: {e}")
                    else:
                        print(f"   ❌ 未找到第 {i+1} 个tour的关闭按钮")

                except Exception as e:
                    print(f"   ❌ 处理第 {i+1} 个tour时出错: {e}")
                    continue

            # 3. 等待所有tour提示消失
            if success_count > 0:
                print("⏳ 等待tour提示完全消失...")
                time.sleep(2)

                # 验证tour是否已消失
                remaining_tours = []
                for selector in tour_selectors:
                    try:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                        for elem in elements:
                            if elem.is_displayed():
                                remaining_tours.append(elem)
                    except:
                        continue

                if remaining_tours:
                    print(f"⚠️ 仍有 {len(remaining_tours)} 个tour提示未消失")
                else:
                    print("✅ 所有tour提示已成功关闭")

            print(f"📋 tour处理完成: 成功关闭 {success_count}/{len(tour_containers)} 个提示")
            return success_count > 0 or len(tour_containers) == 0

        except Exception as e:
            print(f"❌ 处理tour提示失败: {e}")
            return False

    def _find_tour_close_button(self, tour_container):
        """
        在指定的tour容器中查找关闭按钮

        Args:
            tour_container: tour容器元素

        Returns:
            找到的关闭按钮元素或None
        """
        try:
            # 策略1: 使用CSS选择器在容器内查找
            css_selectors = [
                ".jx-tour__content footer .jx-tour-buttons button",
                ".jx-tour__content .jx-tour-buttons button",
                ".jx-tour-buttons button",
                "footer button",
                "button"
            ]

            for selector in css_selectors:
                try:
                    buttons = tour_container.find_elements(By.CSS_SELECTOR, selector)
                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            print(f"      ✅ CSS选择器 '{selector}' 找到按钮")
                            return button
                except Exception as e:
                    print(f"      ⚠️ CSS选择器 '{selector}' 失败: {e}")
                    continue

            # 策略2: 使用XPath在容器内查找
            xpath_selectors = [
                ".//div[contains(@class, 'jx-tour__content')]//footer//div[contains(@class, 'jx-tour-buttons')]//button",
                ".//div[contains(@class, 'jx-tour-buttons')]//button",
                ".//footer//button",
                ".//button"
            ]

            for selector in xpath_selectors:
                try:
                    buttons = tour_container.find_elements(By.XPATH, selector)
                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            print(f"      ✅ XPath选择器 '{selector}' 找到按钮")
                            return button
                except Exception as e:
                    print(f"      ⚠️ XPath选择器 '{selector}' 失败: {e}")
                    continue

            # 策略3: 查找所有按钮，选择最可能的关闭按钮
            try:
                all_buttons = tour_container.find_elements(By.TAG_NAME, "button")
                print(f"      📋 容器内共找到 {len(all_buttons)} 个按钮")

                for i, button in enumerate(all_buttons):
                    if button.is_displayed() and button.is_enabled():
                        button_text = button.text.strip().lower() if button.text else ""
                        button_class = button.get_attribute("class") or ""
                        button_title = button.get_attribute("title") or ""

                        print(f"         {i+1}. 按钮: '{button_text}' (class: {button_class[:20]})")

                        # 优先选择包含关闭相关文字或类名的按钮
                        if any(keyword in button_text for keyword in ['关闭', '跳过', '完成', 'close', 'skip', 'finish', 'done']):
                            print(f"      ✅ 根据文本选择按钮: '{button_text}'")
                            return button
                        elif any(keyword in button_class.lower() for keyword in ['close', 'skip', 'finish', 'done']):
                            print(f"      ✅ 根据class选择按钮: '{button_class}'")
                            return button
                        elif any(keyword in button_title.lower() for keyword in ['关闭', '跳过', 'close', 'skip']):
                            print(f"      ✅ 根据title选择按钮: '{button_title}'")
                            return button

                # 如果没有明确的关闭按钮，选择第一个可用按钮
                if all_buttons:
                    first_button = all_buttons[0]
                    if first_button.is_displayed() and first_button.is_enabled():
                        print("      ⚠️ 未找到明确的关闭按钮，选择第一个可用按钮")
                        return first_button

            except Exception as e:
                print(f"      ❌ 查找所有按钮失败: {e}")

            return None

        except Exception as e:
            print(f"❌ 查找tour关闭按钮失败: {e}")
            return None

    def find_create_product_button(self):
        """查找创建产品按钮 - 根据最新前端更新"""
        try:
            print("🔍 查找创建产品按钮...")

            # 等待页面稳定
            time.sleep(1)

            # 根据你提供的HTML结构，精确匹配创建产品按钮
            create_selectors = [
                # 最精确的选择器 - 根据你提供的HTML结构
                "//button[contains(@class, 'jx-button--primary') and contains(@class, 'pro-button')]//span[contains(text(), '创建产品')]/..",
                "//button[contains(@class, 'jx-button') and contains(@class, 'pro-button')]//span[contains(text(), '创建产品')]/..",
                "button.jx-button.pro-button span:contains('创建产品')",

                # 通过span内容查找父按钮
                "//span[contains(text(), '创建产品')]/parent::button",
                "//span[normalize-space(text())='创建产品']/parent::button",

                # 通过按钮类名和文本内容
                "//button[contains(@class, 'jx-button--primary') and contains(., '创建产品')]",
                "//button[contains(@class, 'pro-button') and contains(., '创建产品')]",
                "//button[contains(@class, 'jx-button') and contains(., '创建产品')]",

                # 精确的CSS选择器
                "button.jx-button.jx-button--primary.pro-button",
                "button.pro-button",

                # 备用选择器
                "//button[contains(text(), '创建产品')]",
                "//button[contains(@class, 'primary') and contains(., '创建')]",
                "button[class*='primary'][class*='pro-button']",

                # 通用创建按钮选择器（作为最后的备选）
                "//button[contains(text(), '创建')]",
                "button[class*='create']",
                "button[class*='add']"
            ]

            print(f"🔍 尝试 {len(create_selectors)} 个选择器...")

            for i, selector in enumerate(create_selectors, 1):
                try:
                    print(f"   尝试选择器 {i}: {selector[:50]}...")

                    if selector.startswith("//"):
                        elements = self.driver.find_elements(By.XPATH, selector)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    print(f"   找到 {len(elements)} 个元素")

                    if elements:
                        for j, element in enumerate(elements):
                            try:
                                if element.is_displayed() and element.is_enabled():
                                    element_text = element.text.strip()
                                    element_class = element.get_attribute("class") or ""
                                    element_style = element.get_attribute("style") or ""

                                    print(f"   ✅ 找到可见按钮 {j+1}: '{element_text}' (class: {element_class[:30]}...)")

                                    # 优先选择包含"创建产品"的按钮
                                    if "创建产品" in element_text:
                                        print(f"✅ 找到创建产品按钮: '{element_text}'")
                                        return element
                                    # 其次选择包含"创建"的按钮
                                    elif "创建" in element_text:
                                        print(f"✅ 找到创建按钮: '{element_text}'")
                                        return element
                                    # 最后选择看起来像创建按钮的元素
                                    elif any(keyword in element_class.lower() for keyword in ['create', 'add', 'primary']):
                                        print(f"✅ 找到疑似创建按钮: '{element_text}' (通过class匹配)")
                                        return element
                            except Exception as e:
                                print(f"   ⚠️ 检查元素 {j+1} 失败: {e}")
                                continue

                except Exception as e:
                    print(f"   ❌ 选择器 {i} 失败: {e}")
                    continue

            # 如果还是没找到，尝试调试页面上所有的按钮
            print("🔍 未找到创建产品按钮，调试页面上所有按钮...")
            try:
                all_buttons = self.driver.find_elements(By.TAG_NAME, "button")
                visible_buttons = []

                for btn in all_buttons:
                    try:
                        if btn.is_displayed() and btn.is_enabled():
                            btn_text = btn.text.strip()
                            btn_class = btn.get_attribute("class") or ""
                            if btn_text:  # 只显示有文本的按钮
                                visible_buttons.append((btn_text, btn_class, btn))
                    except:
                        continue

                print(f"📋 页面上共有 {len(visible_buttons)} 个可见按钮:")
                for i, (text, class_name, btn) in enumerate(visible_buttons[:10], 1):  # 只显示前10个
                    print(f"   {i}. '{text}' (class: {class_name[:40]}...)")

                    # 再次尝试匹配创建相关的按钮
                    if any(keyword in text for keyword in ['创建', '添加', '新建', 'Create', 'Add', 'New']):
                        print(f"✅ 通过调试找到可能的创建按钮: '{text}'")
                        return btn

            except Exception as e:
                print(f"❌ 调试按钮失败: {e}")

            print("❌ 未找到创建产品按钮")
            return None

        except Exception as e:
            print(f"❌ 查找创建产品按钮失败: {e}")
            return None

    def click_create_product(self):
        """点击创建产品按钮并确保弹窗正确打开"""
        try:
            # 1. 点击创建产品前，先关闭可能的遮挡弹窗
            print("🔍 点击创建产品前，检查并关闭遮挡弹窗...")
            self.close_blocking_popups_only()

            # 2. 查找创建产品按钮
            create_button = self.find_create_product_button()
            if not create_button:
                print("❌ 未找到创建产品按钮")
                return False

            # 3. 点击创建产品按钮
            try:
                self.driver.execute_script("arguments[0].click();", create_button)
                print("✅ 成功点击创建产品按钮")
                time.sleep(2)  # 优化：5s -> 2s
            except Exception as e:
                print(f"❌ 点击创建产品按钮失败: {e}")
                return False

            # 4. 验证创建产品弹窗是否正确打开（不再关闭弹窗）
            print("🔍 验证创建产品弹窗是否正确打开...")

            # 检查是否有产品类别输入框（这是创建产品弹窗的特征）
            try:
                category_input = self.driver.find_element(By.CSS_SELECTOR, "input[placeholder='请选择产品类别']")
                if category_input.is_displayed():
                    print("✅ 创建产品弹窗已正确打开（找到产品类别输入框）")
                    return True
            except:
                pass

            # 检查其他创建产品弹窗的特征元素
            product_form_indicators = [
                "input[placeholder='请输入产品标题']",
                "input[placeholder='请输入主货号']",
                "//span[contains(text(), '产品类别')]",
                "//span[contains(text(), '产品标题')]"
            ]

            for indicator in product_form_indicators:
                try:
                    if indicator.startswith("//"):
                        element = self.driver.find_element(By.XPATH, indicator)
                    else:
                        element = self.driver.find_element(By.CSS_SELECTOR, indicator)

                    if element.is_displayed():
                        print(f"✅ 创建产品弹窗已正确打开（找到特征元素）")
                        return True
                except:
                    continue

            print("❌ 创建产品弹窗可能没有正确打开或被遮挡")
            return False

        except Exception as e:
            print(f"❌ 点击创建产品按钮过程失败: {e}")
            return False

    def close_promotion_popup(self):
        """关闭推广弹窗"""
        try:
            print("🔍 查找推广弹窗...")

            # 等待一下让弹窗完全加载
            time.sleep(1)

            # 尝试多种推广弹窗的关闭方式
            promotion_close_selectors = [
                # 常见的关闭按钮选择器
                ".ant-modal-close",
                ".ant-modal-close-x",
                ".modal-close",
                ".close",
                "[aria-label='Close']",
                "[title='关闭']",
                "button[class*='close']",
                ".jx-dialog__close",
                ".jx-modal-close",
                # 推广相关的特定选择器
                ".promotion-modal .close",
                ".ad-modal .close",
                ".popup-close",
                # 通过文本查找关闭按钮
                "//button[contains(text(), '关闭')]",
                "//button[contains(text(), '取消')]",
                "//button[contains(text(), '跳过')]",
                "//span[contains(text(), '×')]",
                "//span[contains(text(), '✕')]"
            ]

            closed_count = 0
            for selector in promotion_close_selectors:
                try:
                    if selector.startswith("//"):
                        elements = self.driver.find_elements(By.XPATH, selector)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            try:
                                # 检查是否是推广相关的弹窗
                                parent = element.find_element(By.XPATH, "./ancestor::div[contains(@class, 'modal') or contains(@class, 'popup') or contains(@class, 'dialog')]")
                                parent_text = parent.text.lower()

                                # 如果包含推广相关关键词，则关闭
                                promotion_keywords = ['推广', '广告', 'promotion', 'ad', '升级', '会员', 'vip']
                                if any(keyword in parent_text for keyword in promotion_keywords):
                                    element.click()
                                    print(f"✅ 关闭推广弹窗 (选择器: {selector})")
                                    closed_count += 1
                                    time.sleep(0.5)
                                    break
                                # 如果找不到父容器或没有推广关键词，也尝试关闭（可能是简单的弹窗）
                                elif len(parent_text) < 50:  # 简单的弹窗通常文本较少
                                    element.click()
                                    print(f"✅ 关闭简单弹窗 (选择器: {selector})")
                                    closed_count += 1
                                    time.sleep(0.5)
                                    break
                            except:
                                # 如果无法检查父容器，直接尝试关闭
                                element.click()
                                print(f"✅ 关闭弹窗 (选择器: {selector})")
                                closed_count += 1
                                time.sleep(0.5)
                                break
                except Exception as e:
                    continue

            if closed_count > 0:
                print(f"✅ 成功关闭 {closed_count} 个推广弹窗")
                time.sleep(1)  # 等待弹窗完全消失
            else:
                print("ℹ️ 未发现需要关闭的推广弹窗")

        except Exception as e:
            print(f"⚠️ 关闭推广弹窗时出错: {e}")

    def close_blocking_popups_only(self):
        """只关闭明显的遮挡弹窗，不关闭功能弹窗"""
        try:
            print("🔍 检查并关闭遮挡弹窗...")

            # 只关闭明显的遮挡弹窗，避免关闭功能弹窗
            blocking_selectors = [
                ".ant-modal-mask + .ant-modal-wrap .ant-modal-close",  # 有遮罩的模态框关闭按钮
                ".modal-backdrop + .modal .close",  # Bootstrap模态框
                "[role='dialog'][aria-modal='true'] .close",  # 明确标记为对话框的关闭按钮
                ".jx-dialog__close",  # jx对话框关闭按钮
                ".jx-overlay-message-box .jx-message-box__close",  # jx消息框关闭按钮
                ".jx-overlay-message-box button",  # jx消息框中的按钮
                "//div[contains(@class, 'jx-overlay-message-box')]//button",  # jx消息框按钮
                "//div[contains(@class, 'mask') or contains(@class, 'backdrop')]//button[contains(@class, 'close')]"  # 有遮罩的关闭按钮
            ]

            closed_count = 0

            for selector in blocking_selectors:
                try:
                    if selector.startswith("//"):
                        close_buttons = self.driver.find_elements(By.XPATH, selector)
                    else:
                        close_buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    for btn in close_buttons:
                        if btn.is_displayed():
                            try:
                                self.driver.execute_script("arguments[0].click();", btn)
                                closed_count += 1
                                print(f"   ✅ 关闭遮挡弹窗 {closed_count}")
                                time.sleep(1)
                            except:
                                pass
                except:
                    continue

            if closed_count == 0:
                print("   ✅ 没有发现遮挡弹窗")
            else:
                print(f"✅ 关闭了 {closed_count} 个遮挡弹窗")

        except Exception as e:
            print(f"❌ 关闭遮挡弹窗过程出错: {e}")

    def close_all_popups_thoroughly(self):
        """彻底关闭所有可能的弹窗"""
        try:
            print("🔍 彻底检查并关闭所有弹窗...")

            # 扩展的关闭按钮选择器
            close_selectors = [
                ".ant-modal-close",
                ".ant-modal-close-x",
                ".modal-close",
                ".close",
                "[aria-label='Close']",
                "[aria-label='close']",
                "button[class*='close']",
                ".jx-dialog__close",
                ".jx-modal-close",
                ".dialog-close",
                "i[class*='close']",
                ".fa-times",
                ".fa-close",
                "//button[contains(@class, 'close')]",
                "//span[contains(@class, 'close')]",
                "//i[contains(@class, 'close')]"
            ]

            closed_count = 0
            max_attempts = 5  # 最多尝试5轮

            for attempt in range(max_attempts):
                found_popup = False

                for selector in close_selectors:
                    try:
                        if selector.startswith("//"):
                            close_buttons = self.driver.find_elements(By.XPATH, selector)
                        else:
                            close_buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)

                        for btn in close_buttons:
                            if btn.is_displayed():
                                try:
                                    self.driver.execute_script("arguments[0].click();", btn)
                                    closed_count += 1
                                    found_popup = True
                                    print(f"   ✅ 关闭弹窗 {closed_count} (选择器: {selector[:30]}...)")
                                    time.sleep(1)
                                except:
                                    pass
                    except:
                        continue

                if not found_popup:
                    break

                time.sleep(1)

            # 按ESC键作为最后的保险
            try:
                from selenium.webdriver.common.keys import Keys
                self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                time.sleep(1)
                print("   ✅ 按ESC键关闭可能的弹窗")
            except:
                pass

            print(f"✅ 弹窗关闭完成，共关闭 {closed_count} 个弹窗")

        except Exception as e:
            print(f"❌ 关闭弹窗过程出错: {e}")

    def fill_product_category(self, custom_category=None):
        """填写产品类别
        
        Args:
            custom_category: 自定义类别路径，如果为None则使用当前产品的类别路径
        """
        try:
            # 选择使用自定义类别还是当前产品的类别路径
            category_path = custom_category or self.current_category_path or self.default_category_path
            category_text = category_path.strip()
            if not category_text:
                print(f"   ⚠️ 类别文本为空，使用默认类别: {category_text}")

            print(f"📝 正在填充产品类别: '{category_text}'")
            print(f"   📊 类别文本长度: {len(category_text)} 字符")

            # 根据调试信息，使用具体的选择器
            category_input = None

            # 查找产品类别输入框（根据调试信息：placeholder='请选择产品类别'）
            try:
                category_input = self.driver.find_element(By.CSS_SELECTOR, "input[placeholder='请选择产品类别']")
                print("✅ 找到产品类别输入框")
            except:
                # 备用选择器
                try:
                    category_input = self.driver.find_element(By.CSS_SELECTOR, "input[placeholder*='类别']")
                    print("✅ 找到产品类别输入框（备用选择器）")
                except:
                    print("❌ 未找到产品类别输入框")
                    return False

            if category_input and category_input.is_displayed():
                # 使用JavaScript点击来避免被其他元素遮挡
                try:
                    category_input.click()
                    print("✅ 使用普通点击成功")
                except:
                    print("⚠️ 普通点击失败，使用JavaScript点击")
                    self.driver.execute_script("arguments[0].click();", category_input)
                time.sleep(1)

                # 不使用clear()方法，直接输入内容（避免触发表单重置）
                # 如果输入框有内容，先选中全部再输入新内容
                try:
                    from selenium.webdriver.common.keys import Keys
                    category_input.send_keys(Keys.CONTROL + "a")  # 全选
                    time.sleep(0.2)
                except:
                    pass

                # 直接输入完整的产品类别路径
                category_input.send_keys(category_text)
                print(f"✅ 已输入完整产品类别路径: '{category_text}'")

                # 等待下拉选项出现
                time.sleep(2)

                # 直接选择第一个选项（系统会自动匹配）
                option_found = False
                try:
                    options = self.driver.find_elements(By.CSS_SELECTOR, "li.jx-cascader__suggestion-item")
                    if options:
                        target_option = options[0]  # 直接选择第一个选项
                        self.driver.execute_script("arguments[0].click();", target_option)
                        print(f"✅ 选择第一个匹配的产品类别选项: '{target_option.text.strip()}'")
                        option_found = True
                        time.sleep(1)
                except Exception as e:
                    print(f"⚠️ 选择类别选项失败: {e}")

                if not option_found:
                    print("⚠️ 未找到下拉选项，尝试其他方法...")

                    # 尝试按键操作
                    try:
                        from selenium.webdriver.common.keys import Keys
                        category_input.send_keys(Keys.ARROW_DOWN)  # 向下箭头
                        time.sleep(1)
                        category_input.send_keys(Keys.ENTER)  # 回车确认
                        print("✅ 使用键盘操作选择第一个选项")
                        option_found = True
                    except:
                        print("⚠️ 键盘操作也失败")

                if option_found:
                    # 验证选择是否真正生效
                    time.sleep(2)
                    try:
                        # 检查产品属性区域是否出现
                        product_attrs = self.driver.find_elements(By.XPATH, "//*[contains(text(), '鞋面材料') or contains(text(), '鞋底材料') or contains(text(), '内里材料')]")
                        if product_attrs:
                            print(f"✅ 产品类别选择成功，属性字段已显示")
                            return True
                        else:
                            print(f"⚠️ 产品类别选择可能未生效，属性字段未显示")
                    except:
                        pass

                    print(f"✅ 产品类别选择完成: {category_text}")
                    return True
                else:
                    print(f"⚠️ 产品类别输入完成但未选择选项，尝试其他方法")

                    # 尝试更多方法来选择
                    try:
                        # 方法1：尝试点击输入框外部然后重新点击
                        self.driver.find_element(By.TAG_NAME, "body").click()
                        time.sleep(1)
                        category_input.click()
                        time.sleep(1)

                        # 方法2：尝试发送Tab键
                        from selenium.webdriver.common.keys import Keys
                        category_input.send_keys(Keys.TAB)
                        time.sleep(1)

                        print("✅ 尝试了其他选择方法")
                        return True
                    except:
                        print(f"⚠️ 其他选择方法也失败")
                        return True

            print("❌ 产品类别输入框不可用")
            return False

        except Exception as e:
            print(f"❌ 填充产品类别失败: {e}")
            return False

    def select_shop(self, shop_name="Shumeng shoes and clothing"):
        """选择店铺"""
        try:
            print(f"🏪 正在选择店铺: '{shop_name}'")

            # 根据用户建议，通过label包含"店铺"来找到店铺输入框
            shop_input = None

            # 策略1：通过label文本找到店铺输入框
            try:
                # 找到包含"店铺"的label元素
                shop_label = self.driver.find_element(By.XPATH, "//label[contains(text(), '店铺')]")
                print("✅ 找到店铺label")

                # 尝试多种方式找到相关的输入框
                input_selectors = [
                    # 通过following-sibling找到后续的输入框容器
                    ".//following-sibling::div//input",
                    ".//following-sibling::div//div[contains(@class, 'jx-select__input-wrapper')]",
                    ".//following-sibling::*//input",
                    # 通过父元素找到同级的输入框
                    "./..//input",
                    "./..//div[contains(@class, 'jx-select__input-wrapper')]",
                    # 通过祖先元素找到输入框
                    "./../..//input",
                    "./../..//div[contains(@class, 'jx-select__input-wrapper')]"
                ]

                for selector in input_selectors:
                    try:
                        input_elements = shop_label.find_elements(By.XPATH, selector)
                        for input_elem in input_elements:
                            if input_elem.is_displayed():
                                shop_input = input_elem
                                print(f"✅ 通过label找到店铺输入框 (选择器: {selector})")
                                break
                        if shop_input:
                            break
                    except:
                        continue

            except Exception as e:
                print(f"⚠️ 通过label查找失败: {e}")

            # 策略2：通过用户提供的精确路径查找
            if not shop_input:
                try:
                    print("🔍 尝试通过用户提供的精确路径查找店铺输入框...")
                    # 用户提供的路径：class=scroll-menu-pane__content的 div 下的第一个 div 下的div下的第一个 div 下的第二个 div 下的 input
                    shop_input = self.driver.find_element(By.CSS_SELECTOR,
                        ".scroll-menu-pane__content > div:first-child > div > div:first-child > div:nth-child(2) > input")
                    print("✅ 通过用户精确路径找到店铺输入框")
                except Exception as e:
                    print(f"⚠️ 通过用户精确路径查找失败: {e}")

            # 策略3：如果通过label找不到，使用placeholder查找
            if not shop_input:
                try:
                    shop_input = self.driver.find_element(By.CSS_SELECTOR, "input[placeholder*='请选择或输入搜索']")
                    print("✅ 通过placeholder找到店铺输入框")
                except:
                    print("⚠️ 通过placeholder查找失败")

            # 策略4：如果还是找不到，查找所有可能的店铺相关输入框
            if not shop_input:
                try:
                    # 查找可能的店铺输入框选择器
                    shop_selectors = [
                        "input[placeholder*='店铺']",
                        "input[placeholder*='选择']",
                        "//input[contains(@placeholder, '店铺')]",
                        "//input[contains(@placeholder, '选择')]",
                        "//div[contains(@class, 'jx-select')]//input",
                        ".jx-select__input-wrapper input"
                    ]

                    for selector in shop_selectors:
                        try:
                            if selector.startswith("//"):
                                elements = self.driver.find_elements(By.XPATH, selector)
                            else:
                                elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                            for element in elements:
                                if element.is_displayed():
                                    # 检查是否是店铺相关的输入框
                                    placeholder = element.get_attribute("placeholder") or ""
                                    if any(keyword in placeholder for keyword in ['店铺', '选择', '搜索']):
                                        shop_input = element
                                        print(f"✅ 通过通用选择器找到店铺输入框: {placeholder}")
                                        break
                            if shop_input:
                                break
                        except:
                            continue
                except Exception as e:
                    print(f"⚠️ 通用选择器查找失败: {e}")

            if not shop_input:
                print("❌ 未找到店铺输入框")
                return False

            # 点击输入框激活
            try:
                self.driver.execute_script("arguments[0].scrollIntoView(true);", shop_input)
                time.sleep(0.5)
                shop_input.click()
                print("✅ 成功点击店铺输入框")
                time.sleep(1)
            except Exception as e:
                print(f"⚠️ 点击店铺输入框失败: {e}")

            # 清空并输入搜索关键词
            try:
                shop_input.clear()
                time.sleep(0.5)
                # 使用完整的店铺名称进行搜索，避免部分搜索可能搜错
                search_keyword = shop_name  # 使用完整店铺名称 "Shumeng shoes and clothing"
                shop_input.send_keys(search_keyword)
                print(f"✅ 已输入完整店铺名称进行搜索: '{search_keyword}'")
                time.sleep(2)  # 等待下拉选项出现
            except Exception as e:
                print(f"❌ 输入搜索关键词失败: {e}")
                return False

            # 查找并选择目标店铺
            try:
                # 等待下拉选项出现
                from selenium.webdriver.support.ui import WebDriverWait
                from selenium.webdriver.support import expected_conditions as EC

                # 使用用户提供的精确class选择器查找店铺选项
                print("🔍 使用精确的class选择器查找店铺选项...")
                option_selectors = [
                    "//li[contains(@class, 'jx-cascader__suggestion-item')]",  # 用户提供的精确选择器
                    f"//li[contains(@class, 'jx-cascader__suggestion-item') and contains(text(), '{shop_name}')]",
                    f"//li[contains(@class, 'jx-cascader__suggestion-item')]//span[contains(text(), '{shop_name}')]",
                    f"//li[contains(@class, 'jx-cascader__suggestion-item') and contains(text(), 'Shumeng')]",
                    f"//li[contains(text(), '{shop_name}')]",  # 备用选择器
                    f"//span[contains(text(), '{shop_name}')]"
                ]

                shop_option = None
                for selector in option_selectors:
                    try:
                        # 等待选项出现
                        WebDriverWait(self.driver, 5).until(
                            EC.presence_of_element_located((By.XPATH, selector))
                        )

                        options = self.driver.find_elements(By.XPATH, selector)
                        for option in options:
                            if option.is_displayed():
                                option_text = option.text.strip()
                                print(f"   找到选项: '{option_text}'")

                                # 检查是否是目标店铺
                                if shop_name in option_text or "Shumeng shoes and clothing" in option_text:
                                    shop_option = option
                                    print(f"✅ 找到目标店铺选项: '{option_text}'")
                                    break

                        if shop_option:
                            break
                    except:
                        continue

                if shop_option:
                    # 点击选择店铺 - 修复点击被拦截问题
                    try:
                        print(f"🎯 准备点击店铺选项: '{shop_option.text.strip()}'")

                        # 🎯 使用多种方法点击店铺选项
                        selection_success = False

                        # 方法1：直接点击选项元素
                        try:
                            print("   方法1：直接点击选项")
                            shop_option.click()
                            time.sleep(1)

                            # 检查是否生效
                            current_value = shop_input.get_attribute("value") or ""
                            if shop_name in current_value or "Shumeng" in current_value:
                                selection_success = True
                                print(f"✅ 方法1成功！当前值: '{current_value}'")
                            else:
                                print(f"⚠️ 方法1未生效，当前值: '{current_value}'")

                        except Exception as direct_error:
                            print(f"⚠️ 方法1失败: {direct_error}")

                        # 方法2：JavaScript点击
                        if not selection_success:
                            try:
                                print("   方法2：JavaScript点击")
                                # 滚动到元素位置
                                self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", shop_option)
                                time.sleep(0.5)

                                # JavaScript点击
                                self.driver.execute_script("arguments[0].click();", shop_option)
                                time.sleep(1)

                                # 检查是否生效
                                current_value = shop_input.get_attribute("value") or ""
                                if shop_name in current_value or "Shumeng" in current_value:
                                    selection_success = True
                                    print(f"✅ 方法2成功！当前值: '{current_value}'")
                                else:
                                    print(f"⚠️ 方法2未生效，当前值: '{current_value}'")

                            except Exception as js_error:
                                print(f"⚠️ 方法2失败: {js_error}")

                        # 方法3：ActionChains点击
                        if not selection_success:
                            try:
                                print("   方法3：ActionChains点击")
                                from selenium.webdriver.common.action_chains import ActionChains
                                actions = ActionChains(self.driver)
                                actions.move_to_element(shop_option).click().perform()
                                time.sleep(1)

                                # 检查是否生效
                                current_value = shop_input.get_attribute("value") or ""
                                if shop_name in current_value or "Shumeng" in current_value:
                                    selection_success = True
                                    print(f"✅ 方法3成功！当前值: '{current_value}'")
                                else:
                                    print(f"⚠️ 方法3未生效，当前值: '{current_value}'")

                            except Exception as action_error:
                                print(f"⚠️ 方法3失败: {action_error}")

                        # 如果所有方法都失败
                        if not selection_success:
                            print("❌ 所有点击方法都失败")
                            return False

                        # 🔒 选择成功后，简单关闭下拉框
                        if selection_success:
                            print("🔒 选择成功，正在关闭下拉框...")

                            # 简单的关闭方法：点击页面其他区域
                            try:
                                # 点击输入框外的区域来关闭下拉框
                                self.driver.execute_script("document.body.click();")
                                time.sleep(0.5)
                                print("✅ 已关闭下拉框")
                            except Exception as e:
                                print(f"⚠️ 关闭下拉框失败: {e}")

                            # 最终验证
                            final_value = shop_input.get_attribute("value") or ""
                            print(f"✅ 店铺选择完成！最终值: '{final_value}'")
                            return True
                        else:
                            print("❌ 店铺选择失败")
                            return False
                    except Exception as e:
                        print(f"❌ 点击店铺选项失败: {e}")
                        return False
                else:
                    print(f"❌ 未找到目标店铺选项: '{shop_name}'")

                    # 显示所有可用选项供调试
                    print("🔍 显示所有可用选项:")
                    try:
                        all_options = self.driver.find_elements(By.XPATH, "//li | //div[contains(@class, 'option')] | //*[contains(@class, 'suggestion')]")
                        for i, option in enumerate(all_options[:10]):  # 只显示前10个
                            if option.is_displayed() and option.text.strip():
                                print(f"   选项{i+1}: '{option.text.strip()}'")
                    except:
                        pass

                    return False

            except Exception as e:
                print(f"❌ 查找店铺选项失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 选择店铺失败: {e}")
            return False

    def click_more_attributes(self):
        """点击更多属性按钮"""
        try:
            print("🔍 正在查找更多属性按钮...")

            # 使用你提供的正确选择器：在 class="expand-button-bar" 的 div 下面
            more_selectors = [
                ".expand-button-bar button",  # expand-button-bar下的按钮
                ".expand-button-bar",  # 直接点击expand-button-bar
                "div.expand-button-bar button",  # 更具体的选择器
                "div.expand-button-bar",  # 备用选择器
                "//div[@class='expand-button-bar']//button",  # XPath选择器
                "//div[@class='expand-button-bar']",  # XPath备用选择器
                "//button[contains(text(), '更多属性')]",  # 原有的备用选择器
                "//span[contains(text(), '更多属性')]"
            ]

            for selector in more_selectors:
                try:
                    if selector.startswith("//"):
                        element = self.driver.find_element(By.XPATH, selector)
                    else:
                        element = self.driver.find_element(By.CSS_SELECTOR, selector)

                    if element.is_displayed():
                        self.driver.execute_script("arguments[0].click();", element)
                        print("✅ 成功点击更多属性")
                        time.sleep(2)
                        return True

                except:
                    continue

            print("⚠️ 未找到更多属性按钮，可能已经展开")
            return True

        except Exception as e:
            print(f"❌ 点击更多属性失败: {e}")
            return False

    def fill_product_attribute(self, attribute_name, attribute_value):
        """填充单个产品属性 - 使用按顺序匹配的方法"""
        try:
            if not attribute_value or str(attribute_value).strip() == "":
                return True

            print(f"📝 正在填充属性: {attribute_name} = {attribute_value}")

            # 使用按顺序匹配的方法：找到容器内的所有label和input-wrapper，按顺序匹配
            try:
                container = self.driver.find_element(By.CSS_SELECTOR, "form.product-attribute-list-container")

                # 获取所有label
                labels = container.find_elements(By.TAG_NAME, "label")
                # 获取所有input-wrapper
                input_wrappers = container.find_elements(By.CSS_SELECTOR, ".jx-select__input-wrapper")

                print(f"   找到 {len(labels)} 个label, {len(input_wrappers)} 个input-wrapper")

                # 查找匹配的label索引
                target_label_index = -1
                for i, label in enumerate(labels):
                    try:
                        if label.is_displayed() and attribute_name in label.text:
                            target_label_index = i
                            print(f"   找到匹配的label索引: {i} ('{label.text.strip()}')")
                            break
                    except:
                        continue

                if target_label_index >= 0 and target_label_index < len(input_wrappers):
                    # 使用对应的input-wrapper
                    target_wrapper = input_wrappers[target_label_index]

                    if target_wrapper.is_displayed():
                        print(f"   找到对应的input-wrapper")

                        # 点击input-wrapper来激活
                        self.driver.execute_script("arguments[0].click();", target_wrapper)
                        time.sleep(1)

                        # 查找wrapper内的input元素
                        try:
                            input_element = target_wrapper.find_element(By.TAG_NAME, "input")
                            if input_element.is_displayed():
                                # 清空并输入内容
                                input_element.clear()
                                input_element.send_keys(str(attribute_value))
                                print(f"   ✅ 成功输入值: {attribute_value}")

                                # 尝试选择第一个下拉选项
                                time.sleep(2)
                                try:
                                    from selenium.webdriver.common.keys import Keys
                                    input_element.send_keys(Keys.ARROW_DOWN)
                                    time.sleep(1)
                                    input_element.send_keys(Keys.ENTER)
                                    print(f"   ✅ 使用键盘选择选项")
                                except:
                                    print(f"   ⚠️ 键盘选择失败，但输入成功")

                                return True
                        except:
                            print(f"   ❌ wrapper内未找到input元素")
                    else:
                        print(f"   ❌ input-wrapper不可见")
                else:
                    print(f"   ❌ 未找到匹配的label或索引超出范围")

            except Exception as e:
                print(f"   ❌ 按顺序匹配失败: {e}")

            # 如果按顺序匹配失败，回退到原来的方法
            print(f"   回退到XPath查找方法...")
            attribute_selectors = [
                f"//form[contains(@class, 'product-attribute-list-container')]//label[contains(text(), '{attribute_name}')]/following-sibling::div//div[contains(@class, 'jx-select__input-wrapper')]//input",
                f"//form[contains(@class, 'product-attribute-list-container')]//label[contains(text(), '{attribute_name}')]/following-sibling::div//*[contains(@class, 'jx-select__input-wrapper')]",
                f"//label[contains(text(), '{attribute_name}')]/following-sibling::div//div[contains(@class, 'jx-select__input-wrapper')]"
            ]

            for i, selector in enumerate(attribute_selectors):
                try:
                    print(f"   尝试选择器{i+1}: {selector}")
                    if selector.startswith("//"):
                        input_elements = self.driver.find_elements(By.XPATH, selector)
                    else:
                        input_elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    print(f"   找到 {len(input_elements)} 个匹配元素")

                    for j, input_element in enumerate(input_elements):
                        if input_element.is_displayed():
                            print(f"   ✅ 找到可见的属性输入框{j+1}: {attribute_name}")

                            # 对于jx-select，可能需要点击来激活
                            try:
                                input_element.click()
                                time.sleep(1)
                                print(f"   点击激活输入框")
                            except:
                                pass

                            # 尝试输入内容
                            try:
                                input_element.clear()
                                input_element.send_keys(str(attribute_value))
                                print(f"   ✅ 成功输入值: {attribute_value}")
                                time.sleep(2)

                                # 尝试选择第一个下拉选项
                                try:
                                    from selenium.webdriver.common.keys import Keys
                                    input_element.send_keys(Keys.ARROW_DOWN)
                                    time.sleep(1)
                                    input_element.send_keys(Keys.ENTER)
                                    print(f"   ✅ 使用键盘选择选项")
                                except:
                                    print(f"   ⚠️ 键盘选择失败，但输入成功")

                                return True
                            except Exception as e:
                                print(f"   ❌ 输入失败: {str(e)[:50]}...")
                                continue

                except Exception as e:
                    print(f"   选择器{i+1}失败: {str(e)[:50]}...")
                    continue

            print(f"⚠️ 未找到属性输入框: {attribute_name}")
            return False

        except Exception as e:
            print(f"❌ 填充属性失败 {attribute_name}: {e}")
            return False

    def create_single_product(self, product_data):
        """创建单个产品 - 简化版本，专门测试产品描述模块"""
        try:
            print(f"\n🏭 开始创建产品: {product_data['产品标题']}")
            print(f"   主货号: {product_data.get('主货号', '(未设置)')}")

            # 1. 先填充产品类别（避免后续被重置）
            print("1️⃣ 填充产品类别...")
            category = product_data.get('产品类别', self.default_category_path)  # 使用Excel中的产品类别
            if not self.fill_product_category(category):
                print("⚠️ 产品类别填充失败，继续执行")

            # 2. 再选择店铺（避免被产品类别重置）
            print("2️⃣ 选择店铺...")
            if not self.select_shop("Shumeng shoes and clothing"):
                print("⚠️ 店铺选择失败，继续执行其他步骤")

            # 等待产品类别选择后系统加载属性字段
            print("⏳ 等待系统加载产品属性字段...")
            time.sleep(3)  # 优化：8s -> 3s

            # 3. 尝试点击产品属性区域来展开属性字段
            print("3️⃣ 尝试展开产品属性...")
            if not self.click_more_attributes():
                print("⚠️ 产品属性展开失败，继续执行")

            # 4. 调试产品属性容器
            print("4️⃣ 调试产品属性容器...")
            self.debug_product_attributes_container()

            # 5. 填充产品属性
            print("5️⃣ 填充产品属性...")
            attributes_to_fill = [
                ('鞋面材料', product_data['鞋面材料']),
                ('鞋底材料', product_data['鞋底材料']),
                ('内里材料', product_data['内里材料']),
                ('闭合方式', product_data['闭合方式']),
                ('适用人群', product_data['适用人群']),
                ('图案', product_data['图案']),
                ('帮高筒高', product_data['帮高筒高']),  # 添加帮高筒高
                ('鞋垫材料', product_data['鞋垫材料']),  # 添加鞋垫材料
                ('鞋头', product_data['鞋头']),
                ('场景', product_data['场景']),
                ('风格', product_data['风格']),
                ('季节', product_data['季节']),
                ('护理说明', product_data['护理说明']),
                ('印花类型', product_data['印花类型']),
                ('产地', product_data['产地']),
                ('外包装形状', product_data['外包装形状']),
                ('外包装类型', product_data['外包装类型'])
            ]

            success_count = 0
            for attr_name, attr_value in attributes_to_fill:
                if self.fill_product_attribute(attr_name, attr_value):
                    success_count += 1
                time.sleep(0.5)  # 短暂等待

            print(f"✅ 成功填充 {success_count}/{len(attributes_to_fill)} 个属性")

            # 6. 填充产品信息 - 包括产地和图片上传
            print("6️⃣ 填充产品信息...")
            self.fill_product_info(product_data)

            # 7. 销售属性/SKU信息处理
            print("7️⃣ 处理销售属性/SKU信息...")
            time.sleep(1)  # 优化：3s -> 1s
            if not self.handle_sku_attributes(product_data):
                print("⚠️ 销售属性/SKU信息处理失败，继续其他步骤")

            # 8. 保存产品
            print("8️⃣ 保存产品...")
            if self.save_product():
                print("✅ 产品保存成功")
            else:
                print("⚠️ 产品保存失败，但产品创建已完成")

            # # 9. 保存产品
            # print("9️⃣ 保存产品...")
            # if self.save_product():
            #     print("✅ 产品保存成功")
            # else:
            #     print("⚠️ 产品保存失败，但产品创建已完成")

            # 记录创建成功到每日限制管理器
            self.daily_limit_manager.record_success()

            return True

        except Exception as e:
            print(f"❌ 创建产品失败: {e}")
            # 记录创建失败到每日限制管理器
            self.daily_limit_manager.record_failure()
            return False

    def batch_create_products(self):
        """批量创建产品"""
        try:
            if not self.product_data or not self.product_data.products:
                print("❌ 没有产品数据可创建")
                return False

            # 检查每日创建限制
            print("\n📊 检查每日创建限制...")
            self.daily_limit_manager.print_daily_summary()

            if not self.daily_limit_manager.can_create_more():
                print("🚫 今日创建配额已用完，无法继续创建产品!")
                return False

            remaining_quota = self.daily_limit_manager.get_remaining_quota()
            print(f"✅ 今日剩余配额: {remaining_quota} 个")

            products = self.product_data.products

            # 如果待创建产品数量超过剩余配额，进行提醒
            if len(products) > remaining_quota:
                print(f"⚠️ 警告: 待创建产品数量({len(products)})超过今日剩余配额({remaining_quota})")
                print(f"📋 将只处理前 {remaining_quota} 个产品")
                products = products[:remaining_quota]

            print(f"\n🚀 开始批量创建 {len(products)} 个产品")

            # 🔧 修复：在开始批量创建前，先彻底关闭所有弹窗
            print("🔄 批量创建前，彻底关闭所有弹窗...")
            self.close_all_popups_thoroughly()
            time.sleep(2)

            # 再次确保弹窗完全关闭
            self.close_all_popups_thoroughly()
            time.sleep(1)
            print("✅ 弹窗清理完成，页面已准备就绪")

            # 🔧 新增：预先批量上传所有产品图片到空间
            print("\n📤 预先批量上传所有产品图片到空间...")
            print("⚠️ 暂时跳过批量上传，将在创建产品时处理图片")
            # if not self.batch_upload_images_to_space():
            #     print("⚠️ 图片批量上传失败，但继续创建产品流程")

            success_count = 0

            for i, product in enumerate(products, 1):
                print(f"\n{'='*60}")
                print(f"正在处理第 {i}/{len(products)} 个产品")
                print(f"{'='*60}")

                # 在每次创建前检查配额
                if not self.daily_limit_manager.can_create_more():
                    print("🚫 今日创建配额已用完，停止创建!")
                    break

                try:
                    # 🔧 修复：每个产品都需要打开创建产品弹窗（包括第一个）
                    print("🔄 打开创建产品弹窗...")
                    if not self.click_create_product():
                        print("❌ 无法打开创建产品弹窗，跳过此产品")
                        continue

                    # 创建产品
                    if self.create_single_product(product):
                        success_count += 1
                        print(f"✅ 产品 {i} 创建成功")

                        # 自动继续处理下一个产品
                        if i < len(products):
                            print(f"🔄 自动继续处理下一个产品...")
                            time.sleep(2)  # 短暂等待，确保系统稳定
                    else:
                        print(f"❌ 产品 {i} 创建失败")

                except Exception as e:
                    print(f"❌ 处理产品 {i} 时出错: {e}")
                    continue

            print(f"\n📊 批量创建完成: 成功 {success_count}/{len(products)} 个产品")
            return True

        except Exception as e:
            print(f"❌ 批量创建产品失败: {e}")
            return False

    def batch_upload_images_to_space(self):
        """批量上传所有产品图片到空间"""
        try:
            print("📤 开始批量上传所有产品图片到空间...")

            if not self.product_data or not self.product_data.products:
                print("❌ 没有产品数据")
                return False

            # 收集所有需要上传的图片目录
            image_dirs = set()
            for product in self.product_data.products:
                merchant_info = product.get('商家信息', '')
                source_info = product.get('货源信息', '')

                if merchant_info and source_info:
                    image_dir = os.path.join("ready", f"{merchant_info}-{source_info}")
                    if os.path.exists(image_dir):
                        image_dirs.add(image_dir)

            if not image_dirs:
                print("❌ 未找到任何图片目录")
                return False

            print(f"📁 找到 {len(image_dirs)} 个图片目录需要上传")

            # 导航到图片空间管理页面
            if not self.navigate_to_image_space():
                print("❌ 无法导航到图片空间页面")
                return False

            # 逐个目录上传图片
            success_count = 0
            for i, image_dir in enumerate(image_dirs, 1):
                print(f"\n[{i}/{len(image_dirs)}] 上传目录: {image_dir}")

                if self.upload_directory_to_space(image_dir):
                    success_count += 1
                    print(f"✅ 目录 {image_dir} 上传成功")
                else:
                    print(f"❌ 目录 {image_dir} 上传失败")

                # 短暂等待，避免请求过快
                time.sleep(2)

            print(f"\n📊 批量上传完成: 成功 {success_count}/{len(image_dirs)} 个目录")

            # 返回到产品管理页面
            self.navigate_back_to_products()

            return success_count > 0

        except Exception as e:
            print(f"❌ 批量上传图片到空间失败: {e}")
            return False

    def navigate_to_image_space(self):
        """导航到图片空间管理页面"""
        try:
            print("🧭 导航到图片空间管理页面...")

            # 方法1: 尝试通过URL直接访问图片空间
            try:
                current_url = self.driver.current_url
                base_url = current_url.split('?')[0].split('#')[0]

                # 尝试常见的图片空间URL路径
                image_space_urls = [
                    f"{base_url}?redirect=%2Fpddkj%2Fimage_space",
                    f"{base_url}?redirect=%2Fpddkj%2Fmedia",
                    f"{base_url}?redirect=%2Fpddkj%2Ffiles",
                    "https://erp.91miaoshou.com/?redirect=%2Fpddkj%2Fimage_space",
                    "https://erp.91miaoshou.com/?redirect=%2Fpddkj%2Fmedia"
                ]

                for url in image_space_urls:
                    try:
                        print(f"🔗 尝试访问: {url}")
                        self.driver.get(url)
                        time.sleep(3)

                        # 检查是否成功到达图片空间页面
                        if self.check_if_image_space_page():
                            print("✅ 成功导航到图片空间页面")
                            return True
                    except:
                        continue

            except Exception as e:
                print(f"⚠️ URL导航失败: {e}")

            # 方法2: 尝试通过菜单导航
            try:
                print("🔍 尝试通过菜单导航...")

                # 查找可能的菜单项
                menu_selectors = [
                    "//a[contains(text(), '图片空间')]",
                    "//a[contains(text(), '媒体库')]",
                    "//a[contains(text(), '文件管理')]",
                    "//span[contains(text(), '图片空间')]",
                    "//span[contains(text(), '媒体库')]"
                ]

                for selector in menu_selectors:
                    try:
                        elements = self.driver.find_elements(By.XPATH, selector)
                        for element in elements:
                            if element.is_displayed():
                                element.click()
                                time.sleep(3)
                                if self.check_if_image_space_page():
                                    print("✅ 通过菜单成功导航到图片空间")
                                    return True
                    except:
                        continue

            except Exception as e:
                print(f"⚠️ 菜单导航失败: {e}")

            print("⚠️ 无法导航到图片空间,将在当前页面尝试上传")
            return True  # 即使无法导航，也继续尝试

        except Exception as e:
            print(f"❌ 导航到图片空间失败: {e}")
            return False

    def check_if_image_space_page(self):
        """检查是否在图片空间页面"""
        try:
            # 检查页面特征元素
            indicators = [
                "//h1[contains(text(), '图片空间')]",
                "//h2[contains(text(), '图片空间')]",
                "//span[contains(text(), '图片空间')]",
                "//div[contains(text(), '图片管理')]",
                ".image-space",
                ".media-library"
            ]

            for indicator in indicators:
                try:
                    if indicator.startswith("//"):
                        elements = self.driver.find_elements(By.XPATH, indicator)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, indicator)

                    if elements and any(elem.is_displayed() for elem in elements):
                        return True
                except:
                    continue

            return False

        except:
            return False

    def upload_directory_to_space(self, image_dir):
        """上传单个目录的图片到空间"""
        try:
            print(f"📤 上传目录 {image_dir} 的图片...")

            # 查找图片文件
            image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
            image_files = []

            for file in os.listdir(image_dir):
                if any(file.lower().endswith(ext) for ext in image_extensions):
                    image_files.append(os.path.join(image_dir, file))

            if not image_files:
                print(f"⚠️ 目录 {image_dir} 中没有图片文件")
                return True  # 不算失败

            print(f"📸 找到 {len(image_files)} 张图片")

            # 尝试找到上传按钮并上传图片
            return self.upload_images_to_space_directly(image_files)

        except Exception as e:
            print(f"❌ 上传目录 {image_dir} 失败: {e}")
            return False

    def upload_images_to_space_directly(self, image_files):
        """直接上传图片到空间"""
        try:
            print("📤 开始直接上传图片到空间...")

            # 查找上传按钮
            upload_button = self.find_space_upload_button()
            if not upload_button:
                print("❌ 未找到空间上传按钮")
                return False

            # 点击上传按钮
            self.driver.execute_script("arguments[0].click();", upload_button)
            print("✅ 成功点击空间上传按钮")
            time.sleep(2)

            # 查找上传弹窗
            upload_popup = self.find_upload_popup()
            if not upload_popup:
                print("❌ 未找到上传弹窗")
                return False

            # 查找本地上传选项
            selector_list = upload_popup.find_element(By.CSS_SELECTOR, ".picture-selector-list")

            # 使用现有的上传逻辑
            return self.upload_images_to_space_via_local_upload(selector_list, image_files)

        except Exception as e:
            print(f"❌ 直接上传图片到空间失败: {e}")
            return False

    def find_space_upload_button(self):
        """查找空间页面的上传按钮"""
        try:
            # 查找可能的上传按钮
            upload_selectors = [
                "//button[contains(text(), '上传图片')]",
                "//button[contains(text(), '上传')]",
                "//span[contains(text(), '上传图片')]",
                "//span[contains(text(), '上传')]",
                "button[class*='upload']",
                ".upload-btn",
                ".upload-button"
            ]

            for selector in upload_selectors:
                try:
                    if selector.startswith("//"):
                        elements = self.driver.find_elements(By.XPATH, selector)
                    else:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            print(f"✅ 找到空间上传按钮: {element.text}")
                            return element
                except:
                    continue

            print("❌ 未找到空间上传按钮")
            return None

        except Exception as e:
            print(f"❌ 查找空间上传按钮失败: {e}")
            return None

    def navigate_back_to_products(self):
        """返回到产品管理页面"""
        try:
            print("🔙 返回到产品管理页面...")

            # 这里需要根据实际的ERP界面结构来实现
            # 暂时什么都不做
            print("⚠️ 返回产品页面功能待实现")
            return True

        except Exception as e:
            print(f"❌ 返回产品页面失败: {e}")
            return False

    def removed_test_product_description_module(self):
        """专门测试产品描述模块的编辑描述按钮"""
        try:
            print("🔍 开始测试产品描述模块...")

            # 等待页面加载
            time.sleep(3)

            # 查找产品描述模块
            print("🔍 查找产品描述模块...")

            # 多种方式查找产品描述相关元素
            description_selectors = [
                "//h3[contains(text(), '产品描述')]",
                "//span[contains(text(), '产品描述')]",
                "//div[contains(text(), '产品描述')]",
                "//*[contains(text(), '产品描述')]"
            ]

            description_section = None
            for selector in description_selectors:
                try:
                    elements = self.driver.find_elements(By.XPATH, selector)
                    for element in elements:
                        if element.is_displayed():
                            description_section = element
                            print(f"✅ 找到产品描述模块: {element.text}")
                            break
                    if description_section:
                        break
                except:
                    continue

            if not description_section:
                print("❌ 未找到产品描述模块")
                return False

            # 查找编辑描述按钮
            print("🔍 查找编辑描述按钮...")

            # 首先查找产品描述区域内的所有按钮
            print("🔍 查找产品描述区域内的所有按钮...")
            try:
                # 获取产品描述模块的父容器
                parent_container = description_section.find_element(By.XPATH, "../..")
                buttons = parent_container.find_elements(By.TAG_NAME, "button")
                print(f"找到 {len(buttons)} 个按钮:")

                edit_button = None
                for i, btn in enumerate(buttons):
                    if btn.is_displayed():
                        btn_text = btn.text.strip()
                        btn_class = btn.get_attribute("class") or ""
                        print(f"  按钮{i+1}: '{btn_text}' (class: {btn_class[:50]}...)")

                        # 优先查找包含"编辑描述"的按钮
                        if "编辑描述" in btn_text:
                            edit_button = btn
                            print(f"✅ 找到编辑描述按钮: '{btn_text}'")
                            break

                # 如果没找到"编辑描述"，查找其他可能的按钮
                if not edit_button:
                    print("🔍 未找到'编辑描述'按钮，查找其他可能的编辑按钮...")
                    for i, btn in enumerate(buttons):
                        if btn.is_displayed():
                            btn_text = btn.text.strip()
                            # 查找包含编辑相关词汇的按钮
                            if any(keyword in btn_text for keyword in ['编辑', '描述', 'edit', 'Edit']):
                                edit_button = btn
                                print(f"✅ 找到可能的编辑按钮: '{btn_text}'")
                                break

                # 如果还是没找到，让用户选择
                if not edit_button and buttons:
                    print("🔍 未找到明确的编辑按钮，显示所有可用按钮:")
                    available_buttons = []
                    for i, btn in enumerate(buttons):
                        if btn.is_displayed() and btn.text.strip():
                            available_buttons.append((i, btn, btn.text.strip()))
                            print(f"  [{i}] {btn.text.strip()}")

                    if available_buttons:
                        # 自动选择第一个看起来像编辑功能的按钮
                        # 或者选择包含"暂未编辑"文本附近的按钮
                        for idx, btn, text in available_buttons:
                            if any(keyword in text for keyword in ['编辑', '添加', '设置', '配置']):
                                edit_button = btn
                                print(f"✅ 自动选择按钮: '{text}'")
                                break

                        # 如果还是没找到合适的，选择第一个按钮
                        if not edit_button:
                            edit_button = available_buttons[0][1]
                            print(f"✅ 默认选择第一个按钮: '{available_buttons[0][2]}'")

            except Exception as e:
                print(f"❌ 查找产品描述区域按钮失败: {e}")
                edit_button = None

            # 如果通过区域查找失败，使用全局选择器
            if not edit_button:
                print("🔍 使用全局选择器查找编辑描述按钮...")
                edit_button_selectors = [
                    "//button[contains(text(), '编辑描述')]",
                    "//span[contains(text(), '编辑描述')]",
                    "//a[contains(text(), '编辑描述')]",
                    "//*[contains(text(), '编辑描述')]",
                    "//button[contains(@class, 'edit')]",
                    ".edit-description-btn",
                    ".description-edit-btn"
                ]

                for selector in edit_button_selectors:
                    try:
                        if selector.startswith("//"):
                            elements = self.driver.find_elements(By.XPATH, selector)
                        else:
                            elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                        for element in elements:
                            if element.is_displayed() and element.is_enabled():
                                edit_button = element
                                print(f"✅ 通过全局选择器找到编辑描述按钮: {element.text}")
                                break
                        if edit_button:
                            break
                    except:
                        continue

            if edit_button:
                # 点击编辑描述按钮
                print("🖱️ 点击编辑描述按钮...")
                try:
                    # 滚动到按钮可见
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", edit_button)
                    time.sleep(1)

                    # 点击按钮
                    self.driver.execute_script("arguments[0].click();", edit_button)
                    print("✅ 成功点击编辑描述按钮")

                    # 等待编辑器加载
                    time.sleep(3)

                    # 验证编辑器是否打开
                    print("🔍 验证编辑器是否打开...")
                    editor_indicators = [
                        "//iframe[contains(@class, 'editor')]",
                        "//div[contains(@class, 'editor')]",
                        "//div[contains(@class, 'rich-text')]",
                        "//textarea[contains(@class, 'description')]"
                    ]

                    editor_found = False
                    for indicator in editor_indicators:
                        try:
                            elements = self.driver.find_elements(By.XPATH, indicator)
                            if elements and any(elem.is_displayed() for elem in elements):
                                print(f"✅ 编辑器已打开: {indicator}")
                                editor_found = True
                                break
                        except:
                            continue

                    if editor_found:
                        print("✅ 产品描述编辑器成功打开")

                        # 继续执行批量图片处理操作
                        print("🔍 开始执行批量图片处理操作...")
                        if self.handle_batch_image_processing():
                            print("✅ 批量图片处理操作成功")
                        else:
                            print("⚠️ 批量图片处理操作失败")

                        return True
                    else:
                        print("⚠️ 编辑器可能未正确打开")
                        return True  # 按钮点击成功，即使编辑器状态不确定

                except Exception as e:
                    print(f"❌ 点击编辑描述按钮失败: {e}")
                    return False
            else:
                print("❌ 未找到任何可用的编辑描述按钮")
                return False

        except Exception as e:
            print(f"❌ 测试产品描述模块失败: {e}")
            return False

    def removed_handle_batch_image_processing(self):
        """处理批量图片处理操作：鼠标悬浮到批量操作，然后点击批量图片处理"""
        try:
            print("🔍 开始处理批量图片处理操作...")

            # 等待编辑器完全加载
            time.sleep(2)

            # 查找批量操作按钮 - 专门在编辑产品描述弹窗内查找
            print("🔍 在编辑产品描述弹窗内查找批量操作按钮...")

            # 首先尝试查找编辑产品描述弹窗容器
            try:
                # 查找编辑产品描述的弹窗容器
                dialog_selectors = [
                    "//div[contains(@class, 'jx-dialog') and contains(.//text(), '编辑产品描述')]",
                    "//div[contains(@class, 'modal') and contains(.//text(), '编辑产品描述')]",
                    "//div[contains(@class, 'dialog') and contains(.//text(), '编辑产品描述')]",
                    "//div[contains(@class, 'popup') and contains(.//text(), '编辑产品描述')]"
                ]

                dialog_container = None
                for selector in dialog_selectors:
                    try:
                        elements = self.driver.find_elements(By.XPATH, selector)
                        for element in elements:
                            if element.is_displayed():
                                dialog_container = element
                                print(f"✅ 找到编辑产品描述弹窗容器")
                                break
                        if dialog_container:
                            break
                    except:
                        continue

                # 如果找到弹窗容器，在其内部查找批量操作按钮
                if dialog_container:
                    print("🔍 在弹窗容器内查找批量操作按钮...")
                    buttons = dialog_container.find_elements(By.TAG_NAME, "button")
                    print(f"弹窗内找到 {len(buttons)} 个按钮:")

                    batch_button = None
                    for i, btn in enumerate(buttons):
                        if btn.is_displayed():
                            btn_text = btn.text.strip()
                            if btn_text:
                                print(f"  弹窗按钮{i+1}: '{btn_text}'")
                                # 查找包含批量操作相关词汇的按钮
                                if any(keyword in btn_text for keyword in ['批量操作', '批量', '操作']):
                                    batch_button = btn
                                    print(f"✅ 在弹窗内找到批量操作按钮: '{btn_text}'")
                                    break
                else:
                    print("❌ 未找到编辑产品描述弹窗容器，使用全局查找...")
                    # 全局查找批量操作按钮
                    batch_operation_selectors = [
                        "//button[contains(text(), '批量操作')]",
                        "//span[contains(text(), '批量操作')]",
                        "//div[contains(text(), '批量操作')]",
                        "//*[contains(text(), '批量操作')]"
                    ]

                    batch_button = None
                    for selector in batch_operation_selectors:
                        try:
                            elements = self.driver.find_elements(By.XPATH, selector)
                            for element in elements:
                                if element.is_displayed() and element.is_enabled():
                                    batch_button = element
                                    print(f"✅ 全局找到批量操作按钮: {element.text}")
                                    break
                            if batch_button:
                                break
                        except:
                            continue

                    if not batch_button:
                        print("🔍 全局查找所有可见按钮...")
                        buttons = self.driver.find_elements(By.TAG_NAME, "button")
                        print(f"全局找到 {len(buttons)} 个按钮:")

                        # 只显示前20个按钮，避免输出过多
                        displayed_count = 0
                        for i, btn in enumerate(buttons):
                            if btn.is_displayed() and displayed_count < 20:
                                btn_text = btn.text.strip()
                                if btn_text:
                                    print(f"  按钮{i+1}: '{btn_text}'")
                                    displayed_count += 1
                                    # 查找包含批量相关词汇的按钮
                                    if any(keyword in btn_text for keyword in ['批量操作', '批量', '操作']) and not batch_button:
                                        batch_button = btn
                                        print(f"✅ 找到可能的批量操作按钮: '{btn_text}'")

                        if displayed_count >= 20:
                            print(f"  ... 还有更多按钮未显示")

            except Exception as e:
                print(f"❌ 查找批量操作按钮失败: {e}")
                batch_button = None

            if not batch_button:
                print("❌ 未找到任何批量操作相关按钮")
                return False

            # 鼠标悬浮到批量操作按钮
            print("🖱️ 鼠标悬浮到批量操作按钮...")
            try:
                from selenium.webdriver.common.action_chains import ActionChains

                # 滚动到按钮可见
                self.driver.execute_script("arguments[0].scrollIntoView(true);", batch_button)
                time.sleep(1)

                # 创建ActionChains对象并执行悬浮操作
                actions = ActionChains(self.driver)
                actions.move_to_element(batch_button).perform()
                print("✅ 成功悬浮到批量操作按钮")

                # 等待下拉菜单出现
                print("⏳ 等待下拉菜单出现...")
                time.sleep(3)  # 增加等待时间

                # 查找批量图片处理选项 - 使用新的策略
                print("🔍 查找批量图片处理选项...")
                print("🔍 使用新策略：查找'文字翻译为英语'的下一个兄弟元素...")

                image_processing_option = None

                # 确保鼠标仍然悬浮在批量操作按钮上
                actions.move_to_element(batch_button).perform()
                time.sleep(2)

                # 全局查找"文字翻译为英语"文案
                try:
                    print("🔍 全局查找'文字翻译为英语'文案...")
                    translate_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '文字翻译为英语')]")

                    for translate_element in translate_elements:
                        if translate_element.is_displayed():
                            print(f"✅ 找到'文字翻译为英语'元素: {translate_element.text}")

                            # 查找下一个兄弟元素
                            try:
                                # 方法1：使用following-sibling查找下一个兄弟元素
                                next_sibling = translate_element.find_element(By.XPATH, "./following-sibling::*[1]")
                                if next_sibling.is_displayed():
                                    sibling_text = next_sibling.text.strip()
                                    print(f"✅ 找到下一个兄弟元素: '{sibling_text}'")

                                    if '批量图片处理' in sibling_text or sibling_text == '批量图片处理':
                                        print(f"✅ 确认找到批量图片处理选项: '{sibling_text}'")
                                        image_processing_option = next_sibling
                                        break
                            except:
                                # 方法2：如果找不到兄弟元素，尝试查找父元素的下一个子元素
                                try:
                                    parent = translate_element.find_element(By.XPATH, "./..")
                                    children = parent.find_elements(By.XPATH, "./*")

                                    # 找到当前元素在子元素列表中的位置
                                    for i, child in enumerate(children):
                                        if child == translate_element and i + 1 < len(children):
                                            next_child = children[i + 1]
                                            if next_child.is_displayed():
                                                child_text = next_child.text.strip()
                                                print(f"✅ 找到父元素的下一个子元素: '{child_text}'")

                                                if '批量图片处理' in child_text or child_text == '批量图片处理':
                                                    print(f"✅ 确认找到批量图片处理选项: '{child_text}'")
                                                    image_processing_option = next_child
                                                    break
                                            break
                                except:
                                    continue

                            if image_processing_option:
                                break

                    if not image_processing_option:
                        print("❌ 未通过'文字翻译为英语'策略找到批量图片处理选项")

                except Exception as e:
                    print(f"❌ 查找'文字翻译为英语'策略失败: {e}")

                # 如果新策略失败，回退到原来的方法
                if not image_processing_option:
                    print("🔍 回退到原来的查找方法...")

                    # 专门查找"批量图片处理"选项，使用更多的选择器
                    image_processing_selectors = [
                        "//li[contains(text(), '批量图片处理')]",
                        "//div[contains(text(), '批量图片处理')]",
                        "//span[contains(text(), '批量图片处理')]",
                        "//a[contains(text(), '批量图片处理')]",
                        "//*[contains(text(), '批量图片处理')]",
                        "//li[contains(text(), '图片处理')]",
                        "//div[contains(text(), '图片处理')]",
                        "//span[contains(text(), '图片处理')]",
                        "//*[contains(text(), '图片处理')]"
                    ]

                    # 多次尝试查找，因为下拉菜单可能需要时间加载
                    for attempt in range(3):
                        print(f"   🔄 第{attempt + 1}次尝试查找批量图片处理选项...")

                        # 确保鼠标仍然悬浮在批量操作按钮上
                        actions.move_to_element(batch_button).perform()
                        time.sleep(1)

                        for selector in image_processing_selectors:
                            try:
                                elements = self.driver.find_elements(By.XPATH, selector)
                                for element in elements:
                                    if element.is_displayed() and element.is_enabled():
                                        element_text = element.text.strip()
                                        if any(keyword in element_text for keyword in ['批量图片处理', '图片处理']):
                                            image_processing_option = element
                                            print(f"✅ 找到批量图片处理选项: '{element_text}'")
                                            break
                                if image_processing_option:
                                    break
                            except:
                                continue

                        if image_processing_option:
                            break

                        print(f"   ⚠️ 第{attempt + 1}次尝试未找到，等待后重试...")
                        time.sleep(2)

                if not image_processing_option:
                    print("❌ 未找到批量图片处理选项")
                    # 尝试查找悬浮后出现的所有选项
                    print("🔍 详细查找悬浮后出现的所有选项...")
                    try:
                        # 确保鼠标仍然悬浮在批量操作按钮上
                        actions.move_to_element(batch_button).perform()
                        time.sleep(2)

                        # 查找可能的下拉菜单容器
                        dropdown_selectors = [
                            ".dropdown-menu",
                            ".menu-list",
                            ".popup-menu",
                            "[role='menu']",
                            ".jx-dropdown-menu",
                            ".ant-dropdown-menu",
                            ".jx-popper",
                            ".popper",
                            "[class*='dropdown']",
                            "[class*='menu']"
                        ]

                        found_dropdown = False
                        for dropdown_selector in dropdown_selectors:
                            try:
                                dropdowns = self.driver.find_elements(By.CSS_SELECTOR, dropdown_selector)
                                for dropdown in dropdowns:
                                    if dropdown.is_displayed():
                                        print(f"✅ 找到下拉菜单容器: {dropdown_selector}")

                                        # 查找菜单项
                                        options = []
                                        option_selectors = ["li", "div", "span", "a"]

                                        for option_selector in option_selectors:
                                            try:
                                                elements = dropdown.find_elements(By.TAG_NAME, option_selector)
                                                for elem in elements:
                                                    if elem.is_displayed():
                                                        elem_text = elem.text.strip()
                                                        if elem_text and len(elem_text) < 100 and elem_text not in options:
                                                            options.append(elem_text)
                                            except:
                                                continue

                                        if options:
                                            print(f"下拉菜单包含 {len(options)} 个选项:")
                                            for i, option_text in enumerate(options):
                                                print(f"  选项{i+1}: '{option_text}'")

                                                # 只查找精确匹配"批量图片处理"的选项
                                                if option_text == '批量图片处理':
                                                    print(f"✅ 找到精确的批量图片处理选项: '{option_text}'")

                                                    # 立即尝试点击这个选项
                                                    try:
                                                        # 重新确保鼠标悬浮在批量操作按钮上
                                                        actions.move_to_element(batch_button).perform()
                                                        time.sleep(1)

                                                        # 查找并点击批量图片处理选项
                                                        batch_image_elements = self.driver.find_elements(By.XPATH, "//*[text()='批量图片处理']")
                                                        for elem in batch_image_elements:
                                                            if elem.is_displayed() and elem.is_enabled():
                                                                print(f"🖱️ 尝试点击批量图片处理选项...")
                                                                actions.move_to_element(elem).click().perform()
                                                                print(f"✅ 成功点击批量图片处理选项!")
                                                                return True  # 立即返回成功
                                                    except Exception as e:
                                                        print(f"❌ 点击批量图片处理选项失败: {e}")
                                                        continue
                                                elif '批量图片处理' in option_text:
                                                    print(f"✅ 找到包含批量图片处理的选项: '{option_text}'")
                                                    # 暂时不点击，继续查找更精确的匹配

                                            if found_dropdown:
                                                break
                                        else:
                                            print(f"下拉菜单容器为空")

                                if found_dropdown:
                                    break
                            except:
                                continue

                        if not found_dropdown:
                            print("❌ 未找到任何下拉菜单容器")

                    except Exception as e:
                        print(f"❌ 查找下拉菜单失败: {e}")

                # 如果在批量操作下拉菜单中没找到"批量图片处理"，尝试查找编辑器中的其他图片功能
                if not image_processing_option:
                    print("❌ 在批量操作下拉菜单中未找到'批量图片处理'选项")
                    print("🔍 尝试在编辑器界面中查找其他图片相关功能...")

                    try:
                        # 查找编辑器工具栏或菜单栏中的图片相关功能
                        print("🔍 查找编辑器工具栏中的图片功能...")

                        # 等待编辑器完全加载
                        time.sleep(2)

                        # 查找可能的工具栏容器
                        toolbar_selectors = [
                            ".toolbar",
                            ".editor-toolbar",
                            ".menu-bar",
                            ".editor-menu",
                            "[class*='toolbar']",
                            "[class*='menu']",
                            ".rich-text-editor .toolbar",
                            ".editor-container .toolbar"
                        ]

                        for toolbar_selector in toolbar_selectors:
                            try:
                                toolbars = self.driver.find_elements(By.CSS_SELECTOR, toolbar_selector)
                                for toolbar in toolbars:
                                    if toolbar.is_displayed():
                                        print(f"✅ 找到工具栏: {toolbar_selector}")

                                        # 在工具栏中查找所有按钮和元素
                                        toolbar_buttons = toolbar.find_elements(By.TAG_NAME, "button")
                                        toolbar_spans = toolbar.find_elements(By.TAG_NAME, "span")
                                        toolbar_divs = toolbar.find_elements(By.TAG_NAME, "div")

                                        all_toolbar_elements = toolbar_buttons + toolbar_spans + toolbar_divs
                                        print(f"工具栏中找到 {len(all_toolbar_elements)} 个元素")

                                        for i, elem in enumerate(all_toolbar_elements):
                                            if elem.is_displayed():
                                                elem_text = elem.text.strip()
                                                elem_title = elem.get_attribute("title") or ""
                                                elem_class = elem.get_attribute("class") or ""

                                                if elem_text or elem_title:
                                                    search_text = (elem_text + elem_title + elem_class).lower()
                                                    if any(keyword in search_text for keyword in ['图片', '批量', '处理', 'image', 'batch', 'process', 'upload', '上传']):
                                                        print(f"  工具栏元素{i+1}: '{elem_text or elem_title}' (class: {elem_class[:30]}...)")

                                                        # 尝试点击这个元素
                                                        try:
                                                            actions.move_to_element(elem).click().perform()
                                                            image_processing_option = elem
                                                            print(f"✅ 成功点击工具栏图片功能: '{elem_text or elem_title}'")
                                                            break
                                                        except:
                                                            continue

                                        if image_processing_option:
                                            break
                            except:
                                continue

                        # 如果工具栏中没找到，查找编辑器内的所有图片相关元素
                        if not image_processing_option:
                            print("🔍 在整个编辑器界面中查找图片相关元素...")

                            # 查找所有可能包含图片功能的元素
                            image_related_selectors = [
                                "//*[contains(text(), '图片')]",
                                "//*[contains(text(), '批量')]",
                                "//*[contains(text(), '处理')]",
                                "//*[contains(@title, '图片')]",
                                "//*[contains(@title, '批量')]",
                                "//*[contains(@title, '处理')]",
                                "//*[contains(@class, 'image')]",
                                "//*[contains(@class, 'batch')]",
                                "//*[contains(@class, 'upload')]"
                            ]

                            for selector in image_related_selectors:
                                try:
                                    elements = self.driver.find_elements(By.XPATH, selector)
                                    for elem in elements:
                                        if elem.is_displayed():
                                            elem_text = elem.text.strip()
                                            elem_title = elem.get_attribute("title") or ""

                                            if elem_text and len(elem_text) < 50:
                                                print(f"  找到图片相关元素: '{elem_text}' (title: '{elem_title}')")

                                                # 如果元素文本包含"批量图片处理"相关词汇，尝试点击
                                                if any(keyword in elem_text for keyword in ['批量图片处理', '图片处理', '批量处理']):
                                                    try:
                                                        actions.move_to_element(elem).click().perform()
                                                        image_processing_option = elem
                                                        print(f"✅ 成功点击图片处理功能: '{elem_text}'")
                                                        break
                                                    except:
                                                        continue

                                    if image_processing_option:
                                        break
                                except:
                                    continue

                    except Exception as e:
                        print(f"❌ 查找编辑器图片功能失败: {e}")

                    if not image_processing_option:
                        print("❌ 在编辑器界面中未找到任何图片处理相关功能")
                        return False

                if image_processing_option:
                    # 点击批量图片处理选项
                    print("🖱️ 点击批量图片处理选项...")
                    try:
                        # 移动到选项并点击
                        actions.move_to_element(image_processing_option).click().perform()
                        print("✅ 成功点击批量图片处理选项")

                        # 等待图片处理界面加载
                        time.sleep(3)

                        # 验证图片处理界面是否打开
                        print("🔍 验证图片处理界面是否打开...")
                        processing_indicators = [
                            "//div[contains(text(), '图片处理')]",
                            "//h3[contains(text(), '图片处理')]",
                            "//span[contains(text(), '图片处理')]",
                            "//*[contains(@class, 'image-processing')]",
                            "//*[contains(@class, 'batch-image')]"
                        ]

                        processing_found = False
                        for indicator in processing_indicators:
                            try:
                                elements = self.driver.find_elements(By.XPATH, indicator)
                                if elements and any(elem.is_displayed() for elem in elements):
                                    print(f"✅ 图片处理界面已打开: {indicator}")
                                    processing_found = True
                                    break
                            except:
                                continue

                        if processing_found:
                            print("✅ 批量图片处理界面成功打开")
                            return True
                        else:
                            print("⚠️ 图片处理界面可能未正确打开，但操作已完成")
                            return True

                    except Exception as e:
                        print(f"❌ 点击批量图片处理选项失败: {e}")
                        return False
                else:
                    print("❌ 在下拉菜单中未找到'批量图片处理'选项")

                    # 显示实际找到的下拉菜单选项，帮助调试
                    print("🔍 显示实际的下拉菜单选项以便调试...")
                    try:
                        # 重新悬浮确保下拉菜单显示
                        actions.move_to_element(batch_button).perform()
                        time.sleep(2)

                        # 查找所有可能的下拉菜单选项
                        dropdown_options = []
                        option_selectors = [
                            "//li[contains(@class, 'dropdown') or contains(@class, 'menu')]",
                            "//div[contains(@class, 'dropdown') or contains(@class, 'menu')]",
                            "//span[contains(@class, 'dropdown') or contains(@class, 'menu')]",
                            "//li",
                            "//div[contains(@role, 'menuitem')]"
                        ]

                        for selector in option_selectors:
                            try:
                                elements = self.driver.find_elements(By.XPATH, selector)
                                for elem in elements:
                                    if elem.is_displayed():
                                        elem_text = elem.text.strip()
                                        if elem_text and len(elem_text) < 50 and elem_text not in dropdown_options:
                                            dropdown_options.append(elem_text)
                            except:
                                continue

                        if dropdown_options:
                            print(f"找到的下拉菜单选项: {dropdown_options}")

                            # 查找包含"图片"关键词的选项
                            for option_text in dropdown_options:
                                if any(keyword in option_text for keyword in ['图片', '处理', 'image', 'Image']):
                                    print(f"✅ 找到可能的图片相关选项: '{option_text}'")
                                    # 尝试点击这个选项
                                    try:
                                        option_element = self.driver.find_element(By.XPATH, f"//*[contains(text(), '{option_text}')]")
                                        if option_element.is_displayed():
                                            actions.move_to_element(option_element).click().perform()
                                            print(f"✅ 成功点击选项: '{option_text}'")
                                            return True
                                    except:
                                        continue
                        else:
                            print("❌ 未找到任何下拉菜单选项")

                    except Exception as e:
                        print(f"❌ 调试下拉菜单失败: {e}")

                    return False

            except Exception as e:
                print(f"❌ 鼠标悬浮操作失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 处理批量图片处理操作失败: {e}")
            return False

    def debug_product_attributes_container(self):
        """调试产品属性容器"""
        try:
            print("🔍 调试产品属性容器...")

            # 查找产品属性容器
            container_selectors = [
                "form.product-attribute-list-container",
                ".product-attribute-list-container",
                "form[class*='product-attribute-list-container']",
                ".jx-form.jx-form--small.jx-form--label-top.product-attribute-list-container",
                "form.jx-form.jx-form--small.jx-form--label-top.product-attribute-list-container.pro-form.pro-form--label-top"
            ]

            for selector in container_selectors:
                try:
                    container = self.driver.find_element(By.CSS_SELECTOR, selector)
                    if container.is_displayed():
                        print(f"✅ 找到产品属性容器: {selector}")

                        # 查找容器内的所有label
                        labels = container.find_elements(By.TAG_NAME, "label")
                        print(f"   容器内有 {len(labels)} 个label:")
                        for i, label in enumerate(labels):
                            try:
                                text = label.text.strip()
                                if text:
                                    print(f"     label{i+1}: '{text}'")
                            except:
                                pass

                        # 查找容器内的所有输入框和相关元素
                        inputs = container.find_elements(By.TAG_NAME, "input")
                        print(f"   容器内有 {len(inputs)} 个input:")
                        for i, input_elem in enumerate(inputs):
                            try:
                                if input_elem.is_displayed():
                                    placeholder = input_elem.get_attribute("placeholder") or ""
                                    class_name = input_elem.get_attribute("class") or ""
                                    print(f"     input{i+1}: placeholder='{placeholder}', class='{class_name[:50]}...'")
                            except:
                                pass

                        # 查找jx-select__selected-item和jx-select__input-wrapper元素
                        selected_items = container.find_elements(By.CSS_SELECTOR, ".jx-select__selected-item")
                        print(f"   容器内有 {len(selected_items)} 个jx-select__selected-item:")
                        for i, item in enumerate(selected_items):
                            try:
                                if item.is_displayed():
                                    class_name = item.get_attribute("class") or ""
                                    print(f"     selected-item{i+1}: class='{class_name[:80]}...'")
                            except:
                                pass

                        input_wrappers = container.find_elements(By.CSS_SELECTOR, ".jx-select__input-wrapper")
                        print(f"   容器内有 {len(input_wrappers)} 个jx-select__input-wrapper:")
                        for i, wrapper in enumerate(input_wrappers):
                            try:
                                if wrapper.is_displayed():
                                    class_name = wrapper.get_attribute("class") or ""
                                    print(f"     input-wrapper{i+1}: class='{class_name[:80]}...'")
                            except:
                                pass

                        return True
                except:
                    continue

            print("❌ 未找到产品属性容器")
            return False

        except Exception as e:
            print(f"❌ 调试产品属性容器失败: {e}")
            return False

    def debug_form_elements(self):
        """调试表单中的所有元素"""
        try:
            print("🔍 调试创建产品弹窗中的所有元素...")

            # 1. 查找所有输入框
            print("\n📝 所有输入框:")
            inputs = self.driver.find_elements(By.TAG_NAME, "input")
            for i, input_elem in enumerate(inputs):
                try:
                    if input_elem.is_displayed():
                        placeholder = input_elem.get_attribute("placeholder") or ""
                        name = input_elem.get_attribute("name") or ""
                        class_name = input_elem.get_attribute("class") or ""
                        value = input_elem.get_attribute("value") or ""
                        if placeholder or name or value:
                            print(f"  输入框{i+1}: placeholder='{placeholder}', name='{name}', value='{value}'")
                            print(f"    class: {class_name[:80]}...")
                except:
                    pass

            # 2. 查找所有标签
            print("\n🏷️ 所有标签:")
            labels = self.driver.find_elements(By.TAG_NAME, "label")
            for i, label in enumerate(labels):
                try:
                    if label.is_displayed():
                        text = label.text.strip()
                        if text and len(text) < 50:
                            print(f"  标签{i+1}: '{text}'")
                except:
                    pass

            # 3. 查找特定属性名相关的元素
            print("\n🔍 查找特定属性名相关的元素:")
            attribute_names = ["产品类别", "鞋面材料", "鞋底材料", "内里材料", "闭合方式", "适用人群", "图案", "鞋头"]

            for attr_name in attribute_names:
                try:
                    elements = self.driver.find_elements(By.XPATH, f"//*[contains(text(), '{attr_name}')]")
                    if elements:
                        print(f"\n  找到'{attr_name}'相关元素:")
                        for j, elem in enumerate(elements):
                            if elem.is_displayed():
                                tag = elem.tag_name
                                text = elem.text.strip()
                                class_name = elem.get_attribute("class") or ""
                                print(f"    {j+1}. <{tag}> '{text}' (class: {class_name[:40]}...)")

                                # 查找该元素附近的输入框
                                try:
                                    parent = elem.find_element(By.XPATH, "..")
                                    nearby_inputs = parent.find_elements(By.TAG_NAME, "input")
                                    for k, inp in enumerate(nearby_inputs):
                                        if inp.is_displayed():
                                            inp_placeholder = inp.get_attribute("placeholder") or ""
                                            inp_class = inp.get_attribute("class") or ""
                                            print(f"      -> 附近输入框{k+1}: placeholder='{inp_placeholder}'")
                                            print(f"         class: {inp_class[:60]}...")
                                except:
                                    pass
                    else:
                        print(f"  未找到包含'{attr_name}'的元素")
                except:
                    pass

            # 4. 查找更多属性按钮
            print("\n🔍 查找更多属性相关按钮:")
            more_keywords = ["更多属性", "更多", "展开", "属性"]
            for keyword in more_keywords:
                try:
                    elements = self.driver.find_elements(By.XPATH, f"//*[contains(text(), '{keyword}')]")
                    if elements:
                        print(f"  找到包含'{keyword}'的元素:")
                        for elem in elements:
                            if elem.is_displayed():
                                tag = elem.tag_name
                                text = elem.text.strip()
                                print(f"    <{tag}> '{text}'")
                except:
                    pass

        except Exception as e:
            print(f"❌ 调试表单元素失败: {e}")

    def fill_product_info(self, product_data):
        """填充产品信息（产品标题、主货号和产地）"""
        try:
            print("📝 开始填充产品信息...")

            # 1. 填充产品标题
            product_title = product_data.get('产品标题', '')
            if product_title:
                print(f"📝 填充产品标题: {product_title}")
                try:
                    # 查找产品标题输入框
                    title_input = self.driver.find_element(By.CSS_SELECTOR, "input[placeholder='请输入产品标题']")
                    if title_input.is_displayed():
                        title_input.clear()
                        title_input.send_keys(product_title)
                        print("✅ 产品标题填充成功")
                    else:
                        print("⚠️ 产品标题输入框不可见")
                except Exception as e:
                    print(f"❌ 产品标题填充失败: {e}")

            # 2. 填充主货号
            main_product_code = product_data.get('主货号', '')
            if main_product_code:
                print(f"📝 填充主货号: {main_product_code}")
                self.fill_main_product_code(main_product_code)

            # 3. 填充产地
            origin = product_data.get('产地', '')
            if origin:
                print(f"📝 填充产地: {origin}")
                self.fill_origin_dropdown(origin)

            # 4. 上传产品轮播图
            print("📝 开始上传产品轮播图...")
            self.upload_product_images(product_data)

        except Exception as e:
            print(f"❌ 填充产品信息失败: {e}")

    def fill_main_product_code(self, main_product_code):
        """填充主货号字段"""
        try:
            print(f"📝 正在填充主货号: {main_product_code}")

            # 查找主货号输入框 - 根据截图，它位于产地字段上方
            main_code_selectors = [
                "input[placeholder='请输入主货号']",
                "input[placeholder*='主货号']",
                "input[placeholder*='货号']"
            ]

            main_code_input = None

            # 尝试通过placeholder查找
            for selector in main_code_selectors:
                try:
                    inputs = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for input_elem in inputs:
                        if input_elem.is_displayed():
                            main_code_input = input_elem
                            print(f"✅ 通过placeholder找到主货号输入框: {selector}")
                            break
                    if main_code_input:
                        break
                except:
                    continue

            # 如果通过placeholder没找到，尝试通过标签文本查找
            if not main_code_input:
                print("🔍 通过placeholder未找到，尝试通过标签文本查找...")
                try:
                    # 查找包含"主货号"文本的标签
                    labels = self.driver.find_elements(By.XPATH, "//label[contains(text(), '主货号')]")
                    for label in labels:
                        try:
                            # 查找标签对应的输入框
                            # 方法1：查找同级或父级元素下的输入框
                            parent = label.find_element(By.XPATH, "./..")
                            inputs = parent.find_elements(By.TAG_NAME, "input")
                            for input_elem in inputs:
                                if input_elem.is_displayed() and input_elem.get_attribute("type") != "hidden":
                                    main_code_input = input_elem
                                    print("✅ 通过标签文本找到主货号输入框")
                                    break
                            if main_code_input:
                                break
                        except:
                            continue
                except Exception as e:
                    print(f"⚠️ 通过标签文本查找失败: {e}")

            # 如果还是没找到，尝试查找产地字段上方的输入框
            if not main_code_input:
                print("🔍 尝试查找产地字段上方的输入框...")
                try:
                    # 先找到产地字段
                    origin_form_item = self.driver.find_element(By.CSS_SELECTOR, ".country-form-item")

                    # 查找产地字段前面的表单项
                    previous_form_items = self.driver.find_elements(By.CSS_SELECTOR, ".jx-form-item")
                    origin_index = -1

                    for i, item in enumerate(previous_form_items):
                        if "country-form-item" in item.get_attribute("class"):
                            origin_index = i
                            break

                    if origin_index > 0:
                        # 检查前面的表单项
                        for i in range(origin_index - 1, max(-1, origin_index - 3), -1):
                            try:
                                form_item = previous_form_items[i]
                                inputs = form_item.find_elements(By.TAG_NAME, "input")
                                for input_elem in inputs:
                                    if input_elem.is_displayed() and input_elem.get_attribute("type") != "hidden":
                                        # 检查是否可能是主货号字段
                                        placeholder = input_elem.get_attribute("placeholder") or ""
                                        if not placeholder or "货号" in placeholder or "主货号" in placeholder:
                                            main_code_input = input_elem
                                            print(f"✅ 找到产地上方的输入框，可能是主货号字段")
                                            break
                                if main_code_input:
                                    break
                            except:
                                continue

                except Exception as e:
                    print(f"⚠️ 查找产地上方输入框失败: {e}")

            if main_code_input:
                try:
                    # 清空并填入主货号
                    main_code_input.clear()
                    main_code_input.send_keys(str(main_product_code))

                    # 验证输入
                    input_value = main_code_input.get_attribute("value")
                    print(f"✅ 主货号填充成功: {input_value}")

                    # 触发change事件
                    self.driver.execute_script("arguments[0].dispatchEvent(new Event('change', {bubbles: true}));", main_code_input)

                except Exception as e:
                    print(f"❌ 填充主货号失败: {e}")
            else:
                print("❌ 未找到主货号输入框")

        except Exception as e:
            print(f"❌ 填充主货号失败: {e}")



    def search_and_select_carousel_images(self, search_keyword):
        """轮播图专用：搜索并选择空间图片（参考外包装方法）"""
        try:
            print(f"🎠 轮播图搜索并选择图片，关键词: {search_keyword}")

            # 等待页面加载完成
            time.sleep(1)

            # 1. 先调试当前页面状态
            print("📋 调试当前页面状态...")
            self.debug_current_page_for_search()

            # 2. 查找搜索输入框
            search_input = self.find_image_search_input()
            if not search_input:
                print("❌ 未找到图片搜索输入框，尝试其他方法...")
                # 尝试直接选择所有图片
                return self.select_all_available_images()

            # 3. 输入搜索关键词
            print(f"📝 清空搜索框并输入关键词: {search_keyword}")
            try:
                # 先点击输入框激活
                search_input.click()
                time.sleep(0.5)

                # 清空输入框
                search_input.clear()
                time.sleep(0.5)

                # 输入搜索关键词
                search_input.send_keys(search_keyword)
                print(f"✅ 输入搜索关键词: {search_keyword}")
                time.sleep(0.5)
            except Exception as e:
                print(f"❌ 输入搜索关键词失败: {e}")
                return False

            # 4. 执行搜索
            search_executed = self.execute_search(search_input)
            if not search_executed:
                print("❌ 搜索执行失败")
                return False

            # 等待搜索结果加载
            time.sleep(1)

            # 5. 直接选择搜索到的图片并确认
            if self.select_all_search_results():
                print("✅ 轮播图搜索、选择和确认完成")
                return True
            else:
                print("❌ 选择搜索结果失败")
                return False

        except Exception as e:
            print(f"❌ 轮播图搜索并选择图片失败: {e}")
            return False

    def select_space_images_with_search(self, search_keyword):
        """从空间图片库搜索并选择图片"""
        try:
            print(f"🔍 在空间图片库中搜索关键词: {search_keyword}")
            time.sleep(1)  # 优化：2s -> 1s

            # 查找空间图片选择对话框
            dialog = self.find_space_image_dialog()
            if not dialog:
                print("❌ 未找到空间图片选择对话框")
                return False

            print("✅ 找到空间图片选择对话框")

            # 在名称输入框输入搜索关键词
            print(f"📝 输入搜索关键词: {search_keyword}")
            if not self.input_search_keyword(dialog, search_keyword):
                print("❌ 输入搜索关键词失败")
                return False

            print("✅ 成功输入搜索关键词")

            # 点击搜索按钮
            print("🔍 点击搜索按钮...")
            if not self.click_search_button(dialog):
                print("❌ 点击搜索按钮失败")
                return False

            print("✅ 成功点击搜索按钮")

            # 等待搜索结果加载（增加等待时间）
            print("⏳ 等待搜索结果加载...")
            time.sleep(3)  # 优化：8s -> 3s

            # 全选搜索出来的图片
            print("📸 全选搜索出来的图片...")
            selected_count = self.select_all_search_images(dialog)
            if selected_count == 0:
                print("❌ 未找到或选择图片")
                return False

            print(f"✅ 成功选择 {selected_count} 张图片")

            # 点击确定按钮
            print("✅ 点击确定按钮...")
            if not self.click_confirm_button_in_dialog(dialog):
                print("❌ 点击确定按钮失败")
                return False

            print("✅ 成功点击确定按钮")

            # 等待对话框关闭
            print("⏳ 等待对话框关闭...")
            time.sleep(2)

            print("✅ 空间图片搜索选择完成")
            return True

        except Exception as e:
            print(f"❌ 空间图片搜索选择失败: {e}")
            return False

    def upload_images_to_space_via_local_upload(self, selector_list, image_files):
        """通过本地上传将图片上传到空间（基于调试结果优化）"""
        try:
            print("📤 开始通过本地上传将图片上传到空间...")

            # 根据调试结果，弹窗已经包含了文件输入框，直接查找并使用
            file_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input[type='file']")
            print(f"🔍 找到 {len(file_inputs)} 个文件输入框")

            if not file_inputs:
                print("❌ 没有找到文件输入框")
                return False

            # 查找图片上传专用的文件输入框（accept包含image）
            image_file_input = None
            for i, file_input in enumerate(file_inputs):
                try:
                    accept_attr = file_input.get_attribute('accept') or ''
                    multiple_attr = file_input.get_attribute('multiple')
                    print(f"   文件输入框{i+1}: accept='{accept_attr}', multiple={multiple_attr}")

                    if 'image' in accept_attr:
                        image_file_input = file_input
                        print(f"✅ 找到图片文件输入框: accept='{accept_attr}'")
                        break
                except:
                    continue

            if not image_file_input:
                # 如果没找到专用的，使用第一个文件输入框
                image_file_input = file_inputs[0]
                print("⚠️ 使用第一个文件输入框")

            # 直接上传图片文件
            return self.upload_images_directly_to_input(image_file_input, image_files)

        except Exception as e:
            print(f"❌ 通过本地上传将图片上传到空间失败: {e}")
            return False

    def upload_images_directly_to_input(self, file_input, image_files):
        """直接向文件输入框上传图片（新方法）"""
        try:
            print(f"📤 开始上传 {len(image_files)} 张图片...")

            # 限制上传数量（避免一次上传太多）
            max_files = 10
            if len(image_files) > max_files:
                image_files = image_files[:max_files]
                print(f"⚠️ 限制上传前 {max_files} 张图片")

            # 准备文件路径
            file_paths = []
            for image_file in image_files:
                abs_path = os.path.abspath(image_file)
                if os.path.exists(abs_path):
                    file_paths.append(abs_path)
                    print(f"   📸 准备上传: {os.path.basename(abs_path)}")
                else:
                    print(f"   ⚠️ 文件不存在: {abs_path}")

            if not file_paths:
                print("❌ 没有有效的图片文件")
                return False

            # 检查文件输入框是否支持多文件
            multiple_attr = file_input.get_attribute('multiple')
            supports_multiple = multiple_attr is not None

            if supports_multiple and len(file_paths) > 1:
                # 方法1：批量上传（推荐，因为input支持multiple=true）
                try:
                    print("🔄 尝试批量上传...")

                    # 将所有文件路径用换行符连接
                    all_paths = '\n'.join(file_paths)

                    # 发送到文件输入框
                    file_input.send_keys(all_paths)

                    print("✅ 批量上传文件路径发送成功")
                    time.sleep(3)  # 等待上传处理

                    return True

                except Exception as e:
                    print(f"⚠️ 批量上传失败: {e}")

            # 方法2：逐个上传（备用方案或单文件上传）
            try:
                print("🔄 尝试逐个上传...")

                success_count = 0
                for i, file_path in enumerate(file_paths, 1):
                    print(f"   📸 上传第 {i}/{len(file_paths)} 张: {os.path.basename(file_path)}")

                    try:
                        # 清空输入框（如果不是第一个文件）
                        if i > 1:
                            file_input.clear()

                        # 发送单个文件路径
                        file_input.send_keys(file_path)

                        # 短暂等待
                        time.sleep(1)

                        success_count += 1

                        # 如果不支持多文件，只上传第一个
                        if not supports_multiple:
                            print("⚠️ 文件输入框不支持多文件，只上传第一张")
                            break

                    except Exception as e:
                        print(f"   ❌ 上传失败: {e}")
                        continue

                print(f"✅ 逐个上传完成: {success_count}/{len(file_paths)} 张成功")
                time.sleep(3)  # 等待最终处理

                return success_count > 0

            except Exception as e:
                print(f"❌ 逐个上传也失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 直接上传图片失败: {e}")
            return False

    def find_upload_popup(self):
        """查找上传弹窗"""
        try:
            popup_selectors = [
                ".jx-popper.is-light.jx-popover",
                ".jx-popper",
                ".upload-popup",
                "[class*='popper']",
                "[class*='popover']"
            ]

            for selector in popup_selectors:
                try:
                    popups = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for popup in popups:
                        if popup.is_displayed():
                            return popup
                except:
                    continue

            return None

        except:
            return None

    def find_use_product_image_button(self, selector_list):
        """查找使用产品图片按钮"""
        try:
            # 查找包含"使用产品图片"文本的div
            child_divs = selector_list.find_elements(By.CSS_SELECTOR, "div")
            for i, div in enumerate(child_divs):
                try:
                    div_text = div.text.strip()
                    if "使用产品图片" in div_text:
                        print(f"✅ 找到使用产品图片按钮（div{i+1}）: '{div_text}'")
                        return div
                except:
                    continue

            print("❌ 未找到使用产品图片按钮")
            return None

        except:
            return None

    def find_space_image_button(self, selector_list):
        """查找选择空间图片按钮"""
        try:
            # 查找包含"选择空间图片"文本的div
            child_divs = selector_list.find_elements(By.CSS_SELECTOR, "div")
            for i, div in enumerate(child_divs):
                try:
                    div_text = div.text.strip()
                    if "选择空间图片" in div_text:
                        print(f"✅ 找到选择空间图片按钮（div{i+1}）: '{div_text}'")
                        return div
                except:
                    continue

            # 备用方法：使用第二个div
            if len(child_divs) >= 2:
                button_text = child_divs[1].text.strip()
                print(f"🔄 备用方法：使用第二个div: '{button_text}'")
                return child_divs[1]

            return None

        except:
            return None

    def select_uploaded_images_from_space(self, search_keyword):
        """直接在当前界面搜索选择刚上传的图片"""
        try:
            print("🔍 尝试直接在当前界面搜索选择图片...")

            # 检查是否已经在空间图片选择界面
            try:
                # 查找空间图片选择的特征元素
                space_indicators = [
                    "input[placeholder*='图片名称']",
                    "input[placeholder*='名称']",
                    ".search-input",
                    "button:contains('搜索')"
                ]

                is_in_space_selection = False
                for indicator in space_indicators:
                    try:
                        elements = self.driver.find_elements(By.CSS_SELECTOR, indicator)
                        if elements and any(elem.is_displayed() for elem in elements):
                            is_in_space_selection = True
                            print(f"✅ 检测到空间图片选择界面: {indicator}")
                            break
                    except:
                        continue

                if is_in_space_selection:
                    # 直接执行搜索选择
                    return self.select_space_images_with_search(search_keyword)
                else:
                    print("⚠️ 当前不在空间图片选择界面")
                    return False

            except Exception as e:
                print(f"⚠️ 检查界面状态失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 直接搜索选择失败: {e}")
            return False

    def retry_select_from_space(self, upload_button, search_keyword):
        """重新打开上传菜单并选择空间图片"""
        try:
            print("🔄 重新打开上传菜单...")

            # 关闭当前弹窗
            try:
                # 尝试按ESC键关闭
                from selenium.webdriver.common.keys import Keys
                self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                time.sleep(1)

                # 或者点击空白区域
                self.driver.execute_script("document.body.click();")
                time.sleep(1)
            except:
                pass

            # 重新点击上传按钮
            try:
                self.driver.execute_script("arguments[0].click();", upload_button)
                time.sleep(3)
                print("✅ 重新点击上传按钮")
            except Exception as e:
                print(f"❌ 重新点击上传按钮失败: {e}")
                return False

            # 查找新的上传弹窗
            new_popup = self.find_upload_popup()
            if not new_popup:
                print("❌ 未找到新的上传弹窗")
                return False

            print("✅ 找到新的上传弹窗")

            # 查找选择空间图片按钮
            try:
                new_selector_list = new_popup.find_element(By.CSS_SELECTOR, ".picture-selector-list")
                space_upload_button = self.find_space_image_button(new_selector_list)

                if space_upload_button:
                    # 点击选择空间图片
                    try:
                        space_upload_button.click()
                        print("✅ 成功点击选择空间图片按钮")
                    except:
                        self.driver.execute_script("arguments[0].click();", space_upload_button)
                        print("✅ 使用JavaScript点击选择空间图片按钮")

                    time.sleep(3)

                    # 执行搜索选择
                    return self.select_space_images_with_search(search_keyword)
                else:
                    print("❌ 未找到选择空间图片按钮")
                    return False

            except Exception as e:
                print(f"❌ 查找选择空间图片按钮失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 重新打开上传菜单失败: {e}")
            return False

    def fill_origin_dropdown(self, origin_value):
        """填充产地下拉选择 - 使用正确的DOM结构路径"""
        try:
            print(f"📝 正在填充产地: {origin_value}")

            # 使用你提供的正确DOM结构：
            # class="jx-form-item jx-form-item--small is-success is-required asterisk-left jx-form-item--label-right country-form-item pro-form-item"
            # 下面的label是产地，同级div下几个层级有class="jx-input__inner"的input

            try:
                # 查找产地表单项容器
                origin_form_item = self.driver.find_element(By.CSS_SELECTOR, ".country-form-item")
                print("✅ 找到产地表单项容器")

                # 在容器内查找jx-input__inner的input
                origin_input = origin_form_item.find_element(By.CSS_SELECTOR, "input.jx-input__inner")

                if origin_input.is_displayed():
                    print("✅ 找到产地输入框")

                    # 点击激活输入框
                    origin_input.click()
                    time.sleep(1)

                    # 输入产地信息
                    origin_input.clear()
                    origin_input.send_keys(origin_value)
                    print(f"✅ 已输入产地: {origin_value}")
                    time.sleep(3)

                    # 尝试选择下拉选项，但要小心不要选择错误的选项
                    try:
                        # 等待下拉选项出现
                        time.sleep(2)

                        # 查找下拉选项
                        print("🔍 查找产地下拉选项...")
                        all_lis = self.driver.find_elements(By.TAG_NAME, "li")
                        cascader_items = []
                        for li in all_lis:
                            if li.is_displayed() and "cascader" in li.get_attribute("class"):
                                li_text = li.text.strip()
                                if li_text:  # 只考虑有文本的选项
                                    cascader_items.append((li, li_text))
                                    print(f"   找到下拉项: {li_text}")

                        # 查找匹配的选项
                        matching_item = None
                        for li, li_text in cascader_items:
                            # 检查是否匹配（支持多种格式）
                            if (li_text == origin_value or
                                li_text == origin_value.replace(" / ", "/") or
                                li_text == origin_value.replace(" / ", " ") or
                                (origin_value.startswith("中国") and li_text.startswith("中国"))):
                                matching_item = li
                                print(f"✅ 找到匹配的下拉选项: {li_text}")
                                break

                        if matching_item:
                            # 点击匹配的选项
                            print(f"🎯 点击匹配的产地选项...")
                            self.driver.execute_script("arguments[0].click();", matching_item)
                            time.sleep(2)

                            # 验证选择是否成功
                            final_value = origin_input.get_attribute("value")
                            print(f"📝 选择后输入框的值: '{final_value}'")

                            if final_value and final_value.strip():
                                print("✅ 产地选择成功")
                                return True
                        else:
                            print("⚠️ 未找到匹配的下拉选项，保持输入的值")
                            # 检查输入框是否还有值
                            current_value = origin_input.get_attribute("value")
                            if current_value and current_value.strip():
                                print(f"✅ 保持输入的产地值: '{current_value}'")
                                return True

                    except Exception as e:
                        print(f"⚠️ 下拉选择过程出错: {e}")
                        # 检查输入框是否还有值
                        current_value = origin_input.get_attribute("value")
                        if current_value and current_value.strip():
                            print(f"✅ 保持输入的产地值: '{current_value}'")
                            return True
                else:
                    print("❌ 产地输入框不可见")

            except Exception as e:
                print(f"⚠️ 使用country-form-item查找失败: {e}")

                # 备用方法：使用完整的class名称查找
                try:
                    full_class_selector = ".jx-form-item.jx-form-item--small.is-success.is-required.asterisk-left.jx-form-item--label-right.country-form-item.pro-form-item"
                    origin_form_item = self.driver.find_element(By.CSS_SELECTOR, full_class_selector)
                    print("✅ 使用完整class找到产地表单项")

                    origin_input = origin_form_item.find_element(By.CSS_SELECTOR, "input.jx-input__inner")
                    if origin_input.is_displayed():
                        print("✅ 找到产地输入框")

                        origin_input.click()
                        time.sleep(1)
                        origin_input.clear()
                        origin_input.send_keys(origin_value)
                        print(f"✅ 已输入产地: {origin_value}")
                        time.sleep(3)

                        # 键盘操作选择
                        try:
                            from selenium.webdriver.common.keys import Keys
                            origin_input.send_keys(Keys.ARROW_DOWN)
                            time.sleep(1)
                            origin_input.send_keys(Keys.ENTER)
                            print("✅ 使用键盘操作选择产地")
                            return True
                        except:
                            print("⚠️ 产地选择失败，但输入成功")
                            return True
                except Exception as e2:
                    print(f"⚠️ 备用方法也失败: {e2}")

            print("❌ 未找到产地输入框")
            return False

        except Exception as e:
            print(f"❌ 填充产地失败: {e}")
            return False

    def upload_product_images(self, product_data):
        """上传产品轮播图"""
        try:
            print("📸 开始上传产品轮播图...")

            # 获取商家信息和货源信息，构建图片目录路径
            merchant_info = product_data.get('商家信息', '')
            source_info = product_data.get('货源信息', '')

            if not merchant_info or not source_info:
                print("❌ 缺少商家信息或货源信息，无法确定图片目录")
                return False

            # 构建图片目录路径和搜索关键词
            import os
            search_keyword = f"{merchant_info}-{source_info}"  # 搜索关键词就是目录名
            image_dir = os.path.join("ready", search_keyword)

            if not os.path.exists(image_dir):
                print(f"❌ 图片目录不存在: {image_dir}")
                return False

            print(f"🔍 轮播图搜索关键词: {search_keyword}")

            # 查找图片文件（支持常见图片格式）
            image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
            image_files = []

            for file in os.listdir(image_dir):
                if any(file.lower().endswith(ext) for ext in image_extensions):
                    image_files.append(os.path.join(image_dir, file))

            # 限制最多10张图片
            image_files = sorted(image_files)[:10]

            if not image_files:
                print(f"❌ 在目录 {image_dir} 中未找到图片文件")
                return False

            print(f"✅ 找到 {len(image_files)} 张图片文件")

            # 快速查找上传图片按钮（已知结构）
            upload_button = None

            try:
                # 直接查找包含"上传图片"文本的按钮（最快方法）
                upload_buttons = self.driver.find_elements(By.XPATH, "//button[contains(text(), '上传图片')]")
                if upload_buttons:
                    upload_button = upload_buttons[0]
                    print(f"✅ 快速找到上传按钮")
                else:
                    # 备用方法：查找符合class的按钮
                    all_buttons = self.driver.find_elements(By.CSS_SELECTOR,
                        "button.jx-button.jx-button--small.jx-tooltip__trigger.pro-button")

                    for button in all_buttons:
                        if button.is_displayed():
                            button_text = button.text or ""
                            if "上传" in button_text:
                                upload_button = button
                                print(f"✅ 找到上传按钮: {button_text}")
                                break

            except Exception as e:
                print(f"❌ 查找上传按钮失败: {e}")

            if not upload_button:
                print("❌ 未找到上传图片按钮")
                return False

            # 点击上传按钮
            self.driver.execute_script("arguments[0].click();", upload_button)
            print("✅ 成功点击上传按钮")
            time.sleep(2)

            # 查找弹出的上传弹窗
            try:
                # 尝试多种弹窗选择器
                popup_selectors = [
                    ".jx-popper.is-light.jx-popover",
                    ".jx-popper",
                    ".jx-popover",
                    "[role='tooltip']",
                    ".upload-popup"
                ]

                upload_popup = None
                for popup_selector in popup_selectors:
                    try:
                        upload_popup = WebDriverWait(self.driver, 3).until(
                            EC.presence_of_element_located((By.CSS_SELECTOR, popup_selector))
                        )
                        if upload_popup.is_displayed():
                            print(f"✅ 找到上传弹窗: {popup_selector}")
                            break
                    except:
                        continue

                if upload_popup:
                    # 使用正确的DOM结构查找本地上传按钮
                    # class="jx-popper is-light jx-popover" 下的 class="picture-selector-list" 下的 class="picture-selector-item pro-upload picture-selector-item"

                    print("🔍 查找正确的本地上传按钮...")
                    local_upload_button = None

                    try:
                        # 查找 picture-selector-list 容器
                        selector_list = upload_popup.find_element(By.CSS_SELECTOR, ".picture-selector-list")
                        print("✅ 找到 picture-selector-list 容器")

                        # 产品轮播图：先本地上传到空间，然后选择最近的图片
                        print("📸 开始处理产品轮播图...")

                        # 步骤1：先本地上传图片到空间
                        print("🔍 步骤1：本地上传图片到空间...")
                        if self.upload_images_to_space_via_local_upload(selector_list, image_files):
                            print("✅ 本地上传到空间成功")
                        else:
                            print("❌ 本地上传到空间失败")
                            return False

                        # 步骤2：上传完成后，选择空间图片
                        print("🔍 步骤2：选择空间图片...")
                        time.sleep(2)  # 等待上传完成

                        # 查找并点击选择空间图片按钮
                        space_upload_button = self.find_space_image_button(selector_list)

                        if space_upload_button and space_upload_button.is_displayed():
                            print(f"✅ 找到'选择空间图片'按钮: '{space_upload_button.text}'")

                            # 点击"选择空间图片"按钮
                            try:
                                space_upload_button.click()
                                print("✅ 成功点击'选择空间图片'按钮")
                            except:
                                self.driver.execute_script("arguments[0].click();", space_upload_button)
                                print("✅ 使用JavaScript点击'选择空间图片'按钮")

                            time.sleep(3)  # 等待空间图片库加载

                            # 使用搜索功能选择轮播图片
                            print(f"🔍 使用搜索功能选择轮播图片，关键词: {search_keyword}")
                            if self.search_and_select_carousel_images(search_keyword):
                                print("✅ 成功通过搜索选择轮播图片")
                                return True
                            else:
                                print("⚠️ 搜索选择失败，尝试手动选择...")
                                # 回退到手动选择
                                if self.select_space_images_manually():
                                    print("✅ 成功选择最近的空间图片，点击确定按钮...")
                                    # 点击确定按钮
                                    if self.click_confirm_button_for_space_images():
                                        print("✅ 成功完成图片选择")
                                        return True
                                    else:
                                        print("⚠️ 点击确定按钮失败")
                                        return False
                                else:
                                    print("❌ 选择空间图片失败")
                                    return False
                        else:
                            print("❌ 未找到'选择空间图片'按钮")
                            return False

                    except Exception as e:
                        print(f"⚠️ 使用CSS选择器查找失败: {e}")

                        # 备用方法：查找包含特定class的div
                        try:
                            print("🔍 使用备用方法查找...")
                            # 调试：显示所有picture-selector相关的元素
                            picture_elements = upload_popup.find_elements(By.XPATH, ".//*[contains(@class, 'picture-selector')]")
                            print(f"✅ 找到 {len(picture_elements)} 个 picture-selector 相关元素")

                            for i, elem in enumerate(picture_elements):
                                if elem.is_displayed():
                                    class_name = elem.get_attribute('class')
                                    text_content = elem.text.strip()
                                    print(f"   元素{i+1}: class='{class_name}' text='{text_content[:20]}'")

                                    # 查找包含 pro-upload 的元素
                                    if 'pro-upload' in class_name and '本地上传' in text_content:
                                        local_upload_button = elem
                                        print(f"✅ 找到本地上传按钮（备用方法）: {class_name}")
                                        break

                            if local_upload_button:
                                self.driver.execute_script("arguments[0].click();", local_upload_button)
                                print("✅ 成功点击本地上传按钮（备用方法）")
                                time.sleep(3)

                                # 点击本地上传后，查找文件输入框并上传图片
                                self.upload_images_to_carousel(image_files, image_dir)

                            else:
                                print("❌ 备用方法也未找到本地上传按钮")

                        except Exception as e2:
                            print(f"❌ 备用方法也失败: {e2}")
                            local_upload_button = None

                    if not local_upload_button:
                        print("❌ 未找到正确的本地上传按钮，无法直接上传到轮播图")
                        return False
                else:
                    print("❌ 未找到上传弹窗")

            except Exception as e:
                print(f"❌ 处理上传弹窗失败: {e}")

            return False

        except Exception as e:
            print(f"❌ 上传产品轮播图失败: {e}")
            return False

    def upload_images_to_carousel(self, image_files, image_dir):
        """使用更可靠的方法上传图片到轮播图"""
        try:
            print("📤 开始上传图片到轮播图...")

            # 等待文件输入框准备就绪
            time.sleep(2)

            # 查找所有文件输入框
            file_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input[type='file']")
            print(f"🔍 总共找到 {len(file_inputs)} 个文件输入框")

            # 详细检查每个文件输入框
            for i, file_input in enumerate(file_inputs):
                try:
                    is_displayed = file_input.is_displayed()
                    style = file_input.get_attribute('style') or ''
                    class_name = file_input.get_attribute('class') or ''
                    accept = file_input.get_attribute('accept') or ''
                    print(f"   文件输入框{i+1}: 可见={is_displayed}, accept='{accept}', class='{class_name[:30]}...'")
                except:
                    print(f"   文件输入框{i+1}: 无法获取属性")

            # 准备所有图片文件的绝对路径
            file_paths = []
            for image_file in image_files:
                abs_path = os.path.abspath(image_file)
                if os.path.exists(abs_path):
                    file_paths.append(abs_path)
                    print(f"   ✅ 图片: {os.path.basename(image_file)}")
                else:
                    print(f"   ❌ 文件不存在: {os.path.basename(image_file)}")

            if not file_paths:
                print("❌ 没有有效的图片文件")
                return False

            # 尝试不同的上传策略
            success = False

            # 策略1：使用最新的文件输入框
            if file_inputs:
                print("📤 策略1：使用最新的文件输入框...")
                file_input = file_inputs[-1]
                success = self.upload_files_via_input(file_input, file_paths, "最新输入框")

            # 策略2：如果策略1失败，尝试所有文件输入框
            if not success and file_inputs:
                print("📤 策略2：尝试所有文件输入框...")
                for i, file_input in enumerate(file_inputs):
                    try:
                        # 跳过明显不可用的输入框
                        style = file_input.get_attribute('style') or ''
                        if 'display: none' in style and 'visibility: hidden' in style:
                            continue

                        success = self.upload_files_via_input(file_input, file_paths, f"输入框{i+1}")
                        if success:
                            break
                    except:
                        continue

            # 策略3：如果还是失败，尝试JavaScript方法
            if not success:
                print("📤 策略3：使用JavaScript方法...")
                success = self.upload_files_via_javascript(file_paths)

            if success:
                print("✅ 图片上传成功！")
                return True
            else:
                print("❌ 所有上传策略都失败了")
                return False

        except Exception as e:
            print(f"❌ 图片上传过程失败: {e}")
            return False

    def upload_files_via_input(self, file_input, file_paths, input_name):
        """通过文件输入框上传文件"""
        try:
            print(f"📤 尝试通过{input_name}上传文件...")

            success_count = 0
            for i, file_path in enumerate(file_paths):
                try:
                    print(f"   上传第{i+1}张: {os.path.basename(file_path)}")

                    # 使用JavaScript设置文件输入框的值
                    self.driver.execute_script("""
                        arguments[0].style.display = 'block';
                        arguments[0].style.visibility = 'visible';
                        arguments[0].style.opacity = '1';
                    """, file_input)

                    # 发送文件路径
                    file_input.send_keys(file_path)
                    success_count += 1
                    print(f"   ✅ 第{i+1}张上传成功")
                    time.sleep(1)  # 等待处理

                except Exception as e:
                    print(f"   ❌ 第{i+1}张上传失败: {e}")
                    continue

            if success_count > 0:
                print(f"✅ 通过{input_name}成功上传 {success_count}/{len(file_paths)} 张图片")
                time.sleep(3)  # 等待系统处理
                return True
            else:
                print(f"❌ 通过{input_name}上传失败")
                return False

        except Exception as e:
            print(f"❌ 通过{input_name}上传过程失败: {e}")
            return False

    def upload_files_via_javascript(self, file_paths):
        """使用JavaScript方法上传文件"""
        try:
            print("📤 尝试使用JavaScript方法上传文件...")

            # 这是一个备用方法，通常用于特殊情况
            # 在大多数情况下，直接的文件输入框方法应该足够
            print("⚠️ JavaScript上传方法需要特殊实现，当前跳过")
            return False

        except Exception as e:
            print(f"❌ JavaScript上传方法失败: {e}")
            return False

    def upload_files_directly(self, file_inputs, image_files):
        """直接使用文件输入框上传文件，避免系统对话框"""
        try:
            print("📤 尝试直接上传文件...")

            if not file_inputs:
                print("❌ 没有可用的文件输入框")
                return False

            # 准备文件路径
            file_paths = []
            for image_file in image_files:
                abs_path = os.path.abspath(image_file)
                if os.path.exists(abs_path):
                    file_paths.append(abs_path)
                    print(f"   ✅ 准备文件: {os.path.basename(image_file)}")
                else:
                    print(f"   ❌ 文件不存在: {os.path.basename(image_file)}")

            if not file_paths:
                print("❌ 没有有效的文件路径")
                return False

            # 尝试每个文件输入框
            for i, file_input in enumerate(file_inputs):
                try:
                    print(f"🔍 尝试文件输入框{i+1}...")

                    # 检查输入框属性
                    accept = file_input.get_attribute('accept') or ''
                    multiple = file_input.get_attribute('multiple')
                    style = file_input.get_attribute('style') or ''

                    print(f"   输入框属性: accept='{accept}', multiple={multiple}, style='{style[:50]}...'")

                    # 跳过明显不适用的输入框
                    if 'video' in accept.lower() and 'image' not in accept.lower():
                        print("   ⚠️ 跳过视频专用输入框")
                        continue

                    # 确保输入框可见
                    self.driver.execute_script("""
                        arguments[0].style.display = 'block';
                        arguments[0].style.visibility = 'visible';
                        arguments[0].style.opacity = '1';
                        arguments[0].style.position = 'static';
                        arguments[0].style.width = 'auto';
                        arguments[0].style.height = 'auto';
                    """, file_input)

                    # 上传文件
                    success_count = 0
                    if multiple:
                        # 支持多文件选择
                        print("   📤 多文件上传...")
                        all_paths = '\n'.join(file_paths)
                        file_input.send_keys(all_paths)
                        success_count = len(file_paths)
                        print(f"   ✅ 批量上传 {success_count} 个文件")
                    else:
                        # 逐个上传
                        print("   📤 逐个文件上传...")
                        for j, file_path in enumerate(file_paths):
                            try:
                                file_input.send_keys(file_path)
                                success_count += 1
                                print(f"   ✅ 上传文件{j+1}: {os.path.basename(file_path)}")
                                time.sleep(0.5)
                            except Exception as e:
                                print(f"   ❌ 上传文件{j+1}失败: {e}")

                    if success_count > 0:
                        print(f"✅ 通过输入框{i+1}成功上传 {success_count} 个文件")
                        time.sleep(3)  # 等待处理
                        return True

                except Exception as e:
                    print(f"   ❌ 输入框{i+1}上传失败: {e}")
                    continue

            print("❌ 所有文件输入框都上传失败")
            return False

        except Exception as e:
            print(f"❌ 直接上传文件失败: {e}")
            return False

    def select_space_images_with_select_all(self):
        """使用全部选中功能从空间图片库选择图片"""
        try:
            print("🔍 查找空间图片库...")
            time.sleep(2)  # 等待图片库加载

            # 查找并点击"全部选中"按钮
            print("🔍 查找全部选中按钮...")
            select_all_selectors = [
                "//button[contains(text(), '全部选中')]",
                "//span[contains(text(), '全部选中')]",
                "//div[contains(text(), '全部选中')]",
                "//*[contains(text(), '全部选中')]",
                "//button[contains(text(), '全选')]",
                "//span[contains(text(), '全选')]",
                "//*[contains(text(), '全选')]"
            ]

            select_all_button = None
            for selector in select_all_selectors:
                try:
                    elements = self.driver.find_elements(By.XPATH, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            select_all_button = element
                            print(f"✅ 找到全部选中按钮: '{element.text}'")
                            break
                    if select_all_button:
                        break
                except Exception as e:
                    print(f"❌ 选择器 '{selector}' 失败: {e}")
                    continue

            if select_all_button:
                # 点击全部选中按钮
                try:
                    select_all_button.click()
                    print("✅ 成功点击全部选中按钮")
                except:
                    self.driver.execute_script("arguments[0].click();", select_all_button)
                    print("✅ 使用JavaScript点击全部选中按钮")

                time.sleep(1)  # 等待选择完成
                print("📸 已全部选中图片")
                selected_count = 1  # 标记为已选择
            else:
                print("❌ 未找到全部选中按钮，尝试手动选择图片...")
                # 回退到原来的手动选择逻辑
                if self.select_space_images_manually():
                    selected_count = 1
                else:
                    selected_count = 0

            print(f"📸 图片选择完成")

            if selected_count > 0:
                # 查找并点击确定按钮 - 需要在对话框内部查找
                print("🔍 查找对话框内的确定按钮...")

                # 使用用户提供的精确路径查找对话框
                print("🎯 使用精确路径查找选择空间图片对话框...")

                dialog_container = None
                try:
                    # 精确路径: .jx-overlay > .jx-overlay-dialog[aria-label="选择空间图片"]
                    overlay_containers = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay")
                    print(f"🔍 找到 {len(overlay_containers)} 个jx-overlay容器")

                    for i, overlay in enumerate(overlay_containers):
                        try:
                            # 查找aria-label="选择空间图片"的对话框
                            space_dialogs = overlay.find_elements(By.CSS_SELECTOR, '.jx-overlay-dialog[aria-label="选择空间图片"]')
                            print(f"   overlay{i+1}中找到 {len(space_dialogs)} 个选择空间图片对话框")

                            if space_dialogs:
                                dialog_container = space_dialogs[0]
                                print(f"✅ 找到选择空间图片对话框容器")
                                break

                        except Exception as e:
                            print(f"   ❌ 检查overlay{i+1}失败: {e}")

                except Exception as e:
                    print(f"❌ 查找jx-overlay容器失败: {e}")

                # 如果精确路径失败，使用备用方法
                if not dialog_container:
                    print("🔄 精确路径失败，尝试备用方法...")
                    dialog_selectors = [
                        '[aria-label="选择空间图片"]',
                        ".jx-overlay-dialog",
                        "[role='dialog']"
                    ]

                    for selector in dialog_selectors:
                        try:
                            dialogs = self.driver.find_elements(By.CSS_SELECTOR, selector)
                            if dialogs:
                                for dialog in dialogs:
                                    if dialog.is_displayed():
                                        dialog_container = dialog
                                        print(f"✅ 备用方法找到对话框容器: {selector}")
                                        break
                            if dialog_container:
                                break
                        except Exception as e:
                            print(f"❌ 备用查找对话框 '{selector}' 失败: {e}")

                confirm_clicked = False
                if dialog_container:
                    # 使用用户提供的精确路径查找footer中的确定按钮
                    print("🎯 使用精确路径查找footer中的确定按钮...")

                    # 精确路径: .jx-overlay-dialog[aria-label="选择空间图片"] > div > footer
                    try:
                        # 查找对话框下的div元素
                        dialog_divs = dialog_container.find_elements(By.CSS_SELECTOR, "div")
                        print(f"🔍 在选择空间图片对话框中找到 {len(dialog_divs)} 个div元素")

                        for i, div in enumerate(dialog_divs):
                            try:
                                # 查找div下的footer
                                footers = div.find_elements(By.CSS_SELECTOR, "footer")
                                if footers:
                                    footer = footers[0]
                                    print(f"   ✅ 在div{i+1}中找到footer")

                                    # 查找footer中的所有按钮
                                    footer_buttons = footer.find_elements(By.CSS_SELECTOR, "button")
                                    print(f"   🔍 footer中找到 {len(footer_buttons)} 个按钮")

                                    for j, btn in enumerate(footer_buttons):
                                        try:
                                            btn_text = btn.text.strip()
                                            btn_class = btn.get_attribute('class') or ''
                                            print(f"      footer按钮{j+1}: '{btn_text}' (class: {btn_class})")

                                            # 检查是否是目标确定按钮
                                            is_target_button = (
                                                'jx-button' in btn_class and
                                                'jx-button--primary' in btn_class and
                                                'jx-button--default' in btn_class and
                                                'pro-button' in btn_class
                                            )

                                            if is_target_button:
                                                print(f"   🎯 找到目标footer确定按钮: '{btn_text}'")

                                                # 点击确定按钮
                                                try:
                                                    btn.click()
                                                    print(f"   ✅ 成功点击footer确定按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break
                                                except:
                                                    # 如果普通点击失败，使用JavaScript点击
                                                    self.driver.execute_script("arguments[0].click();", btn)
                                                    print(f"   ✅ 使用JavaScript点击footer确定按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break

                                        except Exception as e3:
                                            print(f"      ❌ 检查footer按钮{j+1}失败: {e3}")

                                    if confirm_clicked:
                                        break

                            except Exception as e2:
                                print(f"   ❌ 在div{i+1}中查找footer失败: {e2}")
                                continue

                        if confirm_clicked:
                            print("✅ 成功找到并点击footer确定按钮")
                        else:
                            print("❌ 在footer中未找到目标确定按钮")

                    except Exception as e:
                        print(f"❌ 精确路径查找footer失败: {e}")
                        confirm_clicked = False

                    # 如果精确路径失败，使用备用方法
                    if not confirm_clicked:
                        print("🔄 精确路径失败，尝试备用方法...")
                        confirm_selectors = [
                            "footer .jx-button.jx-button--primary.jx-button--default.pro-button",  # 在footer中查找
                            ".jx-dialog__footer .jx-button--primary",  # 在footer中查找primary按钮
                            "button:contains('确定')",
                            ".jx-button--primary",
                            "button"
                        ]

                        for selector in confirm_selectors:
                            try:
                                if "contains" in selector:
                                    # 使用XPath在对话框内查找包含文本的按钮
                                    confirm_buttons = dialog_container.find_elements(By.XPATH, ".//button[contains(text(), '确定')]")
                                else:
                                    confirm_buttons = dialog_container.find_elements(By.CSS_SELECTOR, selector)

                                print(f"🔍 在对话框内找到 {len(confirm_buttons)} 个 '{selector}' 按钮")

                                if confirm_buttons:
                                    for i, btn in enumerate(confirm_buttons):
                                        try:
                                            btn_text = btn.text.strip()
                                            btn_class = btn.get_attribute('class') or ''
                                            print(f"   按钮{i+1}: '{btn_text}' (class: {btn_class[:50]}...)")

                                            # 检查是否是目标确定按钮
                                            is_target_button = (
                                                'jx-button' in btn_class and
                                                'jx-button--primary' in btn_class and
                                                'jx-button--default' in btn_class and
                                                'pro-button' in btn_class
                                            )

                                            if is_target_button:
                                                print(f"   🎯 找到目标确定按钮: '{btn_text}' (完全匹配class)")
                                                # 尝试点击按钮
                                                try:
                                                    btn.click()
                                                    print(f"   ✅ 成功点击目标确定按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break
                                                except:
                                                    # 如果普通点击失败，使用JavaScript点击
                                                    self.driver.execute_script("arguments[0].click();", btn)
                                                    print(f"   ✅ 使用JavaScript点击目标确定按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break
                                            elif btn.is_displayed() and ("确定" in btn_text or "确认" in btn_text):
                                                print(f"   🔍 找到文本匹配的按钮: '{btn_text}'")
                                                # 尝试点击按钮
                                                try:
                                                    btn.click()
                                                    print(f"   ✅ 成功点击文本匹配按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break
                                                except:
                                                    # 如果普通点击失败，使用JavaScript点击
                                                    self.driver.execute_script("arguments[0].click();", btn)
                                                    print(f"   ✅ 使用JavaScript点击文本匹配按钮: '{btn_text}'")
                                                    confirm_clicked = True
                                                    break

                                        except Exception as e:
                                            print(f"   ❌ 检查按钮{i+1}失败: {e}")

                                if confirm_clicked:
                                    break

                            except Exception as e:
                                print(f"❌ 尝试确定按钮 '{selector}' 失败: {e}")
                else:
                    print("❌ 未找到对话框容器")

                if confirm_clicked:
                    time.sleep(3)  # 等待图片加载到轮播图
                    print("✅ 空间图片选择完成")
                    return True
                else:
                    print("❌ 未找到或无法点击确定按钮")
                    return False
            else:
                print("❌ 未选择到任何图片")
                return False

        except Exception as e:
            print(f"❌ 选择空间图片失败: {e}")
            return False

    def select_space_images_manually(self):
        """手动选择空间图片（回退方法）"""
        try:
            print("🔍 手动选择空间图片...")
            time.sleep(2)  # 等待图片库加载

            # 查找图片选择区域
            image_selectors = [
                ".image-item",
                ".picture-item",
                ".space-image",
                "[class*='image-item']",
                ".jx-image",
                "img[src*='jpg'], img[src*='png'], img[src*='jpeg']"
            ]

            selected_count = 0
            for selector in image_selectors:
                try:
                    images = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if images:
                        print(f"🔍 选择器 '{selector}' 找到 {len(images)} 个图片元素")

                        # 尝试选择前几张图片
                        for i, img in enumerate(images[:10]):  # 最多选择10张
                            try:
                                # 检查图片是否可点击
                                if img.is_displayed():
                                    try:
                                        # 先尝试普通点击
                                        img.click()
                                        selected_count += 1
                                        print(f"   ✅ 选择第{i+1}张图片")
                                    except:
                                        # 如果普通点击失败，使用JavaScript点击
                                        self.driver.execute_script("arguments[0].click();", img)
                                        selected_count += 1
                                        print(f"   ✅ 选择第{i+1}张图片（JavaScript）")

                                    time.sleep(0.5)  # 短暂等待

                                    if selected_count >= 10:  # 限制选择数量
                                        break
                            except Exception as e:
                                print(f"   ⚠️ 选择第{i+1}张图片失败: {e}")

                        if selected_count > 0:
                            break  # 如果已经选择了图片，就不用尝试其他选择器了

                except Exception as e:
                    print(f"❌ 选择器 '{selector}' 失败: {e}")

            print(f"📸 总共选择了 {selected_count} 张图片")
            return selected_count > 0

        except Exception as e:
            print(f"❌ 手动选择空间图片失败: {e}")
            return False

    def select_space_images_with_select_all_for_package(self):
        """外包装图片专用：使用全部选中功能从空间图片库选择图片"""
        try:
            print("🔍 查找空间图片库...")
            time.sleep(2)  # 等待图片库加载

            # 查找并点击"全部选中"按钮
            print("🔍 查找全部选中按钮...")
            select_all_selectors = [
                "//button[contains(text(), '全部选中')]",
                "//span[contains(text(), '全部选中')]",
                "//div[contains(text(), '全部选中')]",
                "//*[contains(text(), '全部选中')]",
                "//button[contains(text(), '全选')]",
                "//span[contains(text(), '全选')]",
                "//*[contains(text(), '全选')]"
            ]

            select_all_button = None
            for selector in select_all_selectors:
                try:
                    elements = self.driver.find_elements(By.XPATH, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            select_all_button = element
                            print(f"✅ 找到全部选中按钮: '{element.text}'")
                            break
                    if select_all_button:
                        break
                except Exception as e:
                    print(f"❌ 选择器 '{selector}' 失败: {e}")
                    continue

            if select_all_button:
                # 点击全部选中按钮
                try:
                    select_all_button.click()
                    print("✅ 成功点击全部选中按钮")
                except:
                    self.driver.execute_script("arguments[0].click();", select_all_button)
                    print("✅ 使用JavaScript点击全部选中按钮")

                time.sleep(1)  # 等待选择完成
                print("📸 已全部选中图片")
                selected_count = 1  # 标记为已选择
            else:
                print("❌ 未找到全部选中按钮，尝试手动选择图片...")
                # 回退到原来的手动选择逻辑
                if self.select_space_images_manually():
                    selected_count = 1
                else:
                    selected_count = 0

            print(f"📸 图片选择完成")

            if selected_count > 0:
                # 外包装图片的确定按钮处理
                if self.click_confirm_button_for_package_images():
                    print("✅ 外包装图片确定按钮点击完成")
                    return True
                else:
                    print("❌ 外包装图片确定按钮点击失败")
                    return False
            else:
                print("❌ 没有选择任何图片")
                return False

        except Exception as e:
            print(f"❌ 选择空间图片失败: {e}")
            return False

    def click_confirm_button_for_package_images(self):
        """外包装图片专用：点击确定按钮（增强并发安全性）"""
        try:
            print("🔍 查找外包装图片对话框内的确定按钮...")

            # 添加进程ID标识，便于调试并发问题
            process_id = getattr(self, 'process_id', 'unknown')
            print(f"   🔧 进程 {process_id} 正在查找确定按钮...")

            # 重新查找对话框，避免stale element reference
            time.sleep(2)  # 增加等待时间，确保DOM稳定

            # 首先进行详细的弹窗诊断
            self.diagnose_package_dialog_structure(process_id)

            # 多次重试机制，提高并发环境下的成功率
            max_retries = 3
            confirm_clicked = False

            for retry in range(max_retries):
                if confirm_clicked:
                    break

                print(f"   🔄 第 {retry + 1}/{max_retries} 次尝试查找确定按钮...")

                # 方法1：专门查找外包装图片弹窗的确定按钮
                try:
                    # 查找所有可见的对话框
                    dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                    visible_dialogs = [d for d in dialogs if d.is_displayed()]

                    print(f"   📊 找到 {len(visible_dialogs)} 个可见对话框")

                    # 查找包含"使用产品图片"或"产品图片"的对话框
                    package_dialog = None
                    for i, dialog in enumerate(visible_dialogs):
                        try:
                            dialog_text = dialog.text
                            if "使用产品图片" in dialog_text or "产品图片" in dialog_text or "空间图片" in dialog_text:
                                package_dialog = dialog
                                print(f"   ✅ 找到外包装图片相关对话框 {i+1}")
                                break
                        except:
                            continue

                    # 如果没找到特定对话框，使用最新的对话框
                    if not package_dialog and visible_dialogs:
                        package_dialog = visible_dialogs[-1]
                        print(f"   📋 使用最新的对话框")

                    if package_dialog:
                        # 详细分析这个对话框的结构
                        print(f"   🔍 分析对话框结构...")

                        # 查找所有按钮
                        all_buttons = package_dialog.find_elements(By.TAG_NAME, "button")
                        print(f"      对话框包含 {len(all_buttons)} 个按钮:")

                        for i, btn in enumerate(all_buttons):
                            try:
                                if btn.is_displayed():
                                    btn_text = btn.text.strip()
                                    btn_class = btn.get_attribute("class")
                                    btn_enabled = btn.is_enabled()
                                    print(f"         按钮{i+1}: '{btn_text}' (class: {btn_class[:30]}..., enabled: {btn_enabled})")
                            except:
                                pass

                        # 尝试多种确定按钮查找策略
                        confirm_strategies = [
                            # 策略1：查找包含"确定"文本的按钮
                            (".//button[contains(text(), '确定')]", "确定文本按钮"),
                            (".//span[contains(text(), '确定')]", "确定文本span"),
                            # 策略2：查找primary类型按钮
                            (".//button[contains(@class, 'primary')]", "primary按钮"),
                            (".//button[contains(@class, 'jx-button--primary')]", "jx-primary按钮"),
                            # 策略3：查找footer区域的按钮
                            (".//div[contains(@class, 'footer')]//button", "footer按钮"),
                            (".//div[contains(@class, 'jx-dialog-footer')]//button", "jx-footer按钮"),
                            # 策略4：查找所有可点击按钮（排除取消、关闭）
                            (".//button[not(contains(text(), '取消')) and not(contains(text(), '关闭'))]", "非取消关闭按钮")
                        ]

                        for selector, strategy_name in confirm_strategies:
                            if confirm_clicked:
                                break

                            print(f"      🎯 尝试策略: {strategy_name}")
                            try:
                                buttons = package_dialog.find_elements(By.XPATH, selector)
                                for button in buttons:
                                    if button.is_displayed() and button.is_enabled():
                                        try:
                                            button_text = button.text.strip()
                                            print(f"         尝试点击: '{button_text}'")
                                            button.click()
                                            print(f"✅ 进程 {process_id} 成功点击确定按钮: '{button_text}' (策略: {strategy_name})")
                                            confirm_clicked = True
                                            break
                                        except:
                                            try:
                                                self.driver.execute_script("arguments[0].click();", button)
                                                print(f"✅ 进程 {process_id} 使用JavaScript点击确定按钮: '{button_text}' (策略: {strategy_name})")
                                                confirm_clicked = True
                                                break
                                            except:
                                                continue
                                if confirm_clicked:
                                    break
                            except Exception as e:
                                print(f"         策略 {strategy_name} 失败: {e}")

                    if confirm_clicked:
                        break

                except Exception as e:
                    print(f"❌ 对话框查找失败: {e}")

                # 方法2：直接在页面中查找确定按钮（避免使用缓存的dialog元素）
                if not confirm_clicked:
                    confirm_selectors = [
                        "//button[contains(text(), '确定')]",
                        "//button[contains(text(), '确认')]",
                        "//button[contains(text(), 'OK')]",
                        "//span[contains(text(), '确定')]",
                        "//span[contains(text(), '确认')]"
                    ]

                    for selector in confirm_selectors:
                        try:
                            buttons = self.driver.find_elements(By.XPATH, selector)
                            for button in buttons:
                                if button.is_displayed() and button.is_enabled():
                                    try:
                                        button.click()
                                        print(f"✅ 进程 {process_id} 成功点击确定按钮: '{button.text}'")
                                        confirm_clicked = True
                                        break
                                    except:
                                        self.driver.execute_script("arguments[0].click();", button)
                                        print(f"✅ 进程 {process_id} 使用JavaScript点击确定按钮: '{button.text}'")
                                        confirm_clicked = True
                                        break
                            if confirm_clicked:
                                break
                        except Exception as e:
                            print(f"❌ 选择器 '{selector}' 失败: {e}")

                # 如果这次重试失败，等待后再试
                if not confirm_clicked and retry < max_retries - 1:
                    print(f"   ⏳ 第 {retry + 1} 次尝试失败，等待2秒后重试...")
                    time.sleep(2)

            # 方法3：查找primary按钮
            if not confirm_clicked:
                try:
                    primary_buttons = self.driver.find_elements(By.CSS_SELECTOR, ".jx-button--primary")
                    for button in primary_buttons:
                        if button.is_displayed() and button.is_enabled():
                            try:
                                button.click()
                                print(f"✅ 进程 {process_id} 成功点击primary按钮: '{button.text}'")
                                confirm_clicked = True
                                break
                            except:
                                self.driver.execute_script("arguments[0].click();", button)
                                print(f"✅ 进程 {process_id} 使用JavaScript点击primary按钮: '{button.text}'")
                                confirm_clicked = True
                                break
                except Exception as e:
                    print(f"❌ 查找primary按钮失败: {e}")

            # 方法4：查找关闭按钮
            if not confirm_clicked:
                try:
                    close_buttons = self.driver.find_elements(By.XPATH, "//button[contains(text(), '关闭')]")
                    for button in close_buttons:
                        if button.is_displayed() and button.is_enabled():
                            try:
                                button.click()
                                print(f"✅ 进程 {process_id} 点击关闭按钮完成选择: '{button.text}'")
                                confirm_clicked = True
                                break
                            except:
                                self.driver.execute_script("arguments[0].click();", button)
                                print(f"✅ 进程 {process_id} 使用JavaScript点击关闭按钮: '{button.text}'")
                                confirm_clicked = True
                                break
                except Exception as e:
                    print(f"❌ 查找关闭按钮失败: {e}")

            # 方法5：尝试按ESC键关闭对话框
            if not confirm_clicked:
                try:
                    from selenium.webdriver.common.keys import Keys
                    self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                    print(f"✅ 进程 {process_id} 使用ESC键关闭对话框")
                    confirm_clicked = True
                except Exception as e:
                    print(f"❌ ESC键关闭失败: {e}")

            if confirm_clicked:
                print(f"✅ 进程 {process_id} 确定按钮点击成功，等待对话框关闭...")
                time.sleep(3)  # 增加等待时间，确保对话框完全关闭

                # 验证对话框是否真的关闭了
                try:
                    remaining_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                    visible_dialogs = [d for d in remaining_dialogs if d.is_displayed()]
                    if len(visible_dialogs) == 0:
                        print(f"✅ 进程 {process_id} 对话框已完全关闭")
                    else:
                        print(f"⚠️ 进程 {process_id} 仍有 {len(visible_dialogs)} 个对话框可见")
                except:
                    pass

                return True
            else:
                print(f"❌ 进程 {process_id} 未找到可点击的按钮")

                # 最后的诊断信息
                try:
                    dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                    visible_dialogs = [d for d in dialogs if d.is_displayed()]
                    print(f"   🔍 当前页面有 {len(visible_dialogs)} 个可见对话框")

                    all_buttons = self.driver.find_elements(By.TAG_NAME, "button")
                    visible_buttons = [b for b in all_buttons if b.is_displayed() and b.is_enabled()]
                    print(f"   🔍 当前页面有 {len(visible_buttons)} 个可见可点击按钮")

                    for i, button in enumerate(visible_buttons[:5]):  # 只显示前5个
                        try:
                            button_text = button.text.strip()
                            if button_text:
                                print(f"      按钮{i+1}: '{button_text}'")
                        except:
                            pass
                except:
                    pass

                return False

        except Exception as e:
            print(f"❌ 进程 {process_id} 点击外包装图片确定按钮失败: {e}")
            return False

    def diagnose_package_dialog_structure(self, process_id):
        """诊断外包装图片弹窗结构"""
        try:
            print(f"🔍 进程 {process_id} 开始诊断弹窗结构...")

            # 1. 查找所有对话框
            all_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
            visible_dialogs = [d for d in all_dialogs if d.is_displayed()]
            print(f"   📊 找到 {len(visible_dialogs)} 个可见对话框")

            # 2. 分析每个对话框
            for i, dialog in enumerate(visible_dialogs):
                print(f"   🔍 分析对话框 {i+1}:")
                try:
                    # 获取对话框的基本信息
                    dialog_text = dialog.text[:100] if dialog.text else "无文本"
                    print(f"      文本内容: {dialog_text}...")

                    # 查找对话框中的所有按钮
                    buttons = dialog.find_elements(By.TAG_NAME, "button")
                    print(f"      包含 {len(buttons)} 个按钮:")

                    for j, button in enumerate(buttons):
                        try:
                            if button.is_displayed():
                                button_text = button.text.strip()
                                button_class = button.get_attribute("class")
                                button_enabled = button.is_enabled()
                                print(f"         按钮{j+1}: '{button_text}' (class: {button_class[:50]}..., enabled: {button_enabled})")
                        except Exception as btn_e:
                            print(f"         按钮{j+1}: 获取信息失败 - {btn_e}")

                    # 查找对话框中的footer区域
                    footers = dialog.find_elements(By.CSS_SELECTOR, ".jx-dialog-footer, .dialog-footer, .footer")
                    print(f"      包含 {len(footers)} 个footer区域:")

                    for j, footer in enumerate(footers):
                        try:
                            if footer.is_displayed():
                                footer_buttons = footer.find_elements(By.TAG_NAME, "button")
                                print(f"         footer{j+1}: 包含 {len(footer_buttons)} 个按钮")
                                for k, fb in enumerate(footer_buttons):
                                    if fb.is_displayed():
                                        fb_text = fb.text.strip()
                                        fb_class = fb.get_attribute("class")
                                        print(f"            footer按钮{k+1}: '{fb_text}' (class: {fb_class[:30]}...)")
                        except Exception as footer_e:
                            print(f"         footer{j+1}: 获取信息失败 - {footer_e}")

                except Exception as dialog_e:
                    print(f"      对话框{i+1}分析失败: {dialog_e}")

            # 3. 查找页面中所有可见的确定相关按钮
            print(f"   🔍 页面中所有'确定'相关按钮:")
            confirm_buttons = self.driver.find_elements(By.XPATH, "//*[contains(text(), '确定') or contains(text(), '确认') or contains(text(), 'OK')]")
            visible_confirm_buttons = [b for b in confirm_buttons if b.is_displayed()]

            for i, button in enumerate(visible_confirm_buttons):
                try:
                    button_text = button.text.strip()
                    button_tag = button.tag_name
                    button_class = button.get_attribute("class")
                    button_enabled = button.is_enabled()
                    print(f"      确定按钮{i+1}: '{button_text}' (tag: {button_tag}, class: {button_class[:30]}..., enabled: {button_enabled})")
                except Exception as btn_e:
                    print(f"      确定按钮{i+1}: 获取信息失败 - {btn_e}")

            print(f"   ✅ 进程 {process_id} 弹窗结构诊断完成")

        except Exception as e:
            print(f"❌ 进程 {process_id} 弹窗结构诊断失败: {e}")

    def click_confirm_button_for_space_images(self):
        """点击空间图片选择的确定按钮"""
        try:
            print("🔍 查找对话框内的确定按钮...")

            # 使用精确路径查找对话框
            print("🎯 使用精确路径查找选择空间图片对话框...")

            dialog_container = None
            try:
                # 精确路径: .jx-overlay > .jx-overlay-dialog[aria-label="选择空间图片"]
                overlay_containers = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay")
                print(f"🔍 找到 {len(overlay_containers)} 个jx-overlay容器")

                for i, overlay in enumerate(overlay_containers):
                    try:
                        # 查找aria-label="选择空间图片"的对话框
                        space_dialogs = overlay.find_elements(By.CSS_SELECTOR, '.jx-overlay-dialog[aria-label="选择空间图片"]')
                        print(f"   overlay{i+1}中找到 {len(space_dialogs)} 个选择空间图片对话框")

                        if space_dialogs:
                            dialog_container = space_dialogs[0]
                            print(f"✅ 找到选择空间图片对话框容器")
                            break

                    except Exception as e:
                        print(f"   ❌ 检查overlay{i+1}失败: {e}")

            except Exception as e:
                print(f"❌ 查找jx-overlay容器失败: {e}")

            # 如果精确路径失败，使用备用方法
            if not dialog_container:
                print("🔄 精确路径失败，尝试备用方法...")
                dialog_selectors = [
                    '[aria-label="选择空间图片"]',
                    ".jx-overlay-dialog",
                    "[role='dialog']"
                ]

                for selector in dialog_selectors:
                    try:
                        dialogs = self.driver.find_elements(By.CSS_SELECTOR, selector)
                        if dialogs:
                            for dialog in dialogs:
                                if dialog.is_displayed():
                                    dialog_container = dialog
                                    print(f"✅ 备用方法找到对话框容器: {selector}")
                                    break
                        if dialog_container:
                            break
                    except Exception as e:
                        print(f"❌ 备用查找对话框 '{selector}' 失败: {e}")

            if not dialog_container:
                print("❌ 未找到对话框容器")
                return False

            # 查找并点击确定按钮
            confirm_clicked = False

            # 使用精确路径查找footer中的确定按钮
            print("🎯 使用精确路径查找footer中的确定按钮...")

            try:
                # 查找对话框下的div元素
                dialog_divs = dialog_container.find_elements(By.CSS_SELECTOR, "div")
                print(f"🔍 在选择空间图片对话框中找到 {len(dialog_divs)} 个div元素")

                for i, div in enumerate(dialog_divs):
                    try:
                        # 查找div下的footer
                        footers = div.find_elements(By.CSS_SELECTOR, "footer")
                        if footers:
                            footer = footers[0]
                            print(f"   ✅ 在div{i+1}中找到footer")

                            # 查找footer中的所有按钮
                            footer_buttons = footer.find_elements(By.CSS_SELECTOR, "button")
                            print(f"   🔍 footer中找到 {len(footer_buttons)} 个按钮")

                            for j, btn in enumerate(footer_buttons):
                                try:
                                    btn_text = btn.text.strip()
                                    btn_class = btn.get_attribute('class') or ''
                                    print(f"      footer按钮{j+1}: '{btn_text}' (class: {btn_class})")

                                    # 检查是否是目标确定按钮
                                    is_target_button = (
                                        'jx-button' in btn_class and
                                        'jx-button--primary' in btn_class and
                                        'jx-button--default' in btn_class and
                                        'pro-button' in btn_class
                                    )

                                    if is_target_button:
                                        print(f"   🎯 找到目标footer确定按钮: '{btn_text}'")

                                        # 点击确定按钮
                                        try:
                                            btn.click()
                                            print(f"   ✅ 成功点击footer确定按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break
                                        except:
                                            # 如果普通点击失败，使用JavaScript点击
                                            self.driver.execute_script("arguments[0].click();", btn)
                                            print(f"   ✅ 使用JavaScript点击footer确定按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break

                                except Exception as e3:
                                    print(f"      ❌ 检查footer按钮{j+1}失败: {e3}")

                            if confirm_clicked:
                                break

                    except Exception as e2:
                        print(f"   ❌ 在div{i+1}中查找footer失败: {e2}")
                        continue

            except Exception as e:
                print(f"❌ 精确路径查找footer失败: {e}")

            # 如果精确路径失败，使用备用方法
            if not confirm_clicked:
                print("🔄 精确路径失败，尝试备用方法...")
                confirm_selectors = [
                    "footer .jx-button.jx-button--primary.jx-button--default.pro-button",  # 在footer中查找
                    ".jx-dialog__footer .jx-button--primary",  # 在footer中查找primary按钮
                    "button:contains('确定')",
                    ".jx-button--primary",
                    "button"
                ]

                for selector in confirm_selectors:
                    try:
                        if "contains" in selector:
                            # 使用XPath在对话框内查找包含文本的按钮
                            confirm_buttons = dialog_container.find_elements(By.XPATH, ".//button[contains(text(), '确定')]")
                        else:
                            confirm_buttons = dialog_container.find_elements(By.CSS_SELECTOR, selector)

                        print(f"🔍 在对话框内找到 {len(confirm_buttons)} 个 '{selector}' 按钮")

                        if confirm_buttons:
                            for i, btn in enumerate(confirm_buttons):
                                try:
                                    btn_text = btn.text.strip()
                                    btn_class = btn.get_attribute('class') or ''
                                    print(f"   按钮{i+1}: '{btn_text}' (class: {btn_class[:50]}...)")

                                    # 检查是否是目标确定按钮
                                    is_target_button = (
                                        'jx-button' in btn_class and
                                        'jx-button--primary' in btn_class and
                                        'jx-button--default' in btn_class and
                                        'pro-button' in btn_class
                                    )

                                    if is_target_button:
                                        print(f"   🎯 找到目标确定按钮: '{btn_text}' (完全匹配class)")
                                        # 尝试点击按钮
                                        try:
                                            btn.click()
                                            print(f"   ✅ 成功点击目标确定按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break
                                        except:
                                            # 如果普通点击失败，使用JavaScript点击
                                            self.driver.execute_script("arguments[0].click();", btn)
                                            print(f"   ✅ 使用JavaScript点击目标确定按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break
                                    elif btn.is_displayed() and ("确定" in btn_text or "确认" in btn_text):
                                        print(f"   🔍 找到文本匹配的按钮: '{btn_text}'")
                                        # 尝试点击按钮
                                        try:
                                            btn.click()
                                            print(f"   ✅ 成功点击文本匹配按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break
                                        except:
                                            # 如果普通点击失败，使用JavaScript点击
                                            self.driver.execute_script("arguments[0].click();", btn)
                                            print(f"   ✅ 使用JavaScript点击文本匹配按钮: '{btn_text}'")
                                            confirm_clicked = True
                                            break

                                except Exception as e:
                                    print(f"   ❌ 检查按钮{i+1}失败: {e}")

                        if confirm_clicked:
                            break

                    except Exception as e:
                        print(f"❌ 尝试确定按钮 '{selector}' 失败: {e}")

            if confirm_clicked:
                time.sleep(3)  # 等待图片加载到轮播图
                print("✅ 空间图片确定按钮点击完成")
                return True
            else:
                print("❌ 未找到或无法点击确定按钮")
                return False

        except Exception as e:
            print(f"❌ 点击确定按钮失败: {e}")
            return False

    def handle_sku_attributes(self, product_data):
        """处理销售属性/SKU信息"""
        try:
            print("🎨 开始处理销售属性/SKU信息...")

            # 首先检查页面是否已经加载了SKU相关元素
            print("🔍 检查SKU相关元素是否已加载...")

            # 调试：显示product_data中的所有键值对
            print("🔍 调试product_data内容:")
            for key, value in product_data.items():
                print(f"   {key}: {value}")

            # 1. 处理颜色属性（支持多颜色）
            color_value = product_data.get('规格1_颜色', '') or product_data.get('颜色', '')
            print(f"🔍 获取到的颜色值: '{color_value}'")
            color_list = self.parse_color_list(color_value)

            if color_list:
                print(f"🎨 处理颜色属性列表: {color_list}")
                if not self.select_multiple_colors(color_list):
                    print("⚠️ 颜色属性选择失败")
                    return False

                # 颜色选择后等待页面更新
                time.sleep(2)
            else:
                print("⚠️ 未找到颜色信息，跳过颜色属性处理")

            # 2. 处理尺码属性
            size_value = product_data.get('规格2_尺码', '') or product_data.get('尺码', '')
            print(f"🔍 获取到的尺码值: '{size_value}'")
            print(f"🔍 product_data中的所有尺码相关字段:")
            for key, value in product_data.items():
                if '尺码' in key or 'size' in key.lower():
                    print(f"   {key}: '{value}'")

            if size_value:
                print(f"📏 处理尺码属性: {size_value}")

                # 首先根据尺码范围判断男鞋女鞋并设置对应的模版数据，同时根据产品类别确定具体子类型
                self.determine_shoe_type_and_set_size_data(size_value, product_data)

                if not self.select_size_attribute(size_value):
                    print("⚠️ 尺码属性选择失败")
                    return False

                # 选择尺码后，等待SKU表格生成，然后填写尺寸和重量数据
                print("⏳ 等待SKU表格生成...")
                time.sleep(3)  # 等待表格生成

                print("📏 开始填写SKU尺寸和重量数据...")
                if self.fill_sku_dimensions_and_weight():
                    print("✅ SKU尺寸和重量数据填写成功")
                else:
                    print("⚠️ SKU尺寸和重量数据填写失败，但继续执行")
                # 3. 填充SKU预览图
                print("🖼️ 开始填充SKU预览图...")
                if self.fill_sku_preview_images():
                    print("✅ SKU预览图填充成功")
                else:
                    print("⚠️ SKU预览图填充失败，但继续执行")

                # 4. 批量修改供货价
                supply_price = product_data.get('供货价', '')
                if supply_price:
                    print(f"💰 开始批量修改供货价: {supply_price}")
                    if self.batch_modify_supply_price(supply_price):
                        print("✅ 供货价批量修改成功")
                    else:
                        print("⚠️ 供货价批量修改失败，但继续执行")

                # 5. 批量修改建议售价
                suggested_price = product_data.get('建议售价', '')
                if suggested_price:
                    print(f"💰 开始批量修改建议售价: {suggested_price}")
                    if self.batch_modify_suggested_price(suggested_price):
                        print("✅ 建议售价批量修改成功")
                    else:
                        print("⚠️ 建议售价批量修改失败，但继续执行")

                # 6. 批量修改SKU分类
                sku_category = product_data.get('SKU分类', '')
                if sku_category:
                    print(f"🔄 开始批量修改SKU分类: {sku_category}")
                    if self.batch_modify_sku_category():
                        print("✅ SKU分类批量修改成功")
                    else:
                        print("⚠️ SKU分类批量修改失败，但继续执行")
            else:
                print("⚠️ 未找到尺码信息，跳过尺码属性和长宽高填写")
                print("🔍 可用的product_data字段:")
                for key in sorted(product_data.keys()):
                    print(f"   {key}: '{product_data[key]}'")
                # 继续执行其他步骤，不返回False

            # 7. 处理包装类型信息
            print("📦 开始处理包装类型信息...")
            if self.handle_package_info(product_data):
                print("✅ 包装类型信息处理成功")
            else:
                print("⚠️ 包装类型信息处理失败，但继续执行")

            print("✅ 销售属性/SKU信息处理完成")
            return True

        except Exception as e:
            print(f"❌ 处理销售属性/SKU信息失败: {e}")
            return False

    def parse_color_list(self, color_value):
        """将颜色字符串拆分为列表"""
        if not color_value:
            return []

        if isinstance(color_value, list):
            return [str(item).strip() for item in color_value if str(item).strip()]

        colors = []
        for part in re.split(r'[，,、;\n]+', str(color_value)):
            value = part.strip()
            if value:
                colors.append(value)
        return colors

    def ensure_color_rows(self, required_count):
        """确保颜色行数量达到要求"""
        try:
            color_info_list = self.driver.find_element(By.CSS_SELECTOR, ".color-info-list")
        except Exception:
            print("❌ ensure_color_rows: 未找到颜色信息列表")
            return False

        for _ in range(10):
            current = self._count_color_units(color_info_list)
            if current >= required_count:
                print(f"✅ 颜色行数量已满足: {current}/{required_count}")
                return True
            if not self.add_color_row(current):
                return False
            time.sleep(0.5)
        print(f"❌ 无法确保颜色行数量达到 {required_count}")
        return False

    def select_multiple_colors(self, color_list):
        """按照顺序选择多个颜色"""
        try:
            # 记录实际选择的颜色，后续SKU表格识别颜色列时使用
            self.actual_selected_colors = list(color_list)
            required_rows = len(color_list)
            if not self.ensure_color_rows(required_rows):
                print("❌ 无法创建足够的颜色行")
                return False

            for index, color_name in enumerate(color_list):
                print(f"🎨 处理第 {index + 1} 个颜色: {color_name}")
                if not self.select_color_attribute(color_name, color_index=index):
                    print(f"❌ 颜色 '{color_name}' 选择失败")
                    return False
                time.sleep(0.5)  # 让页面渲染

            return True
        except Exception as e:
            print(f"❌ 处理多颜色失败: {e}")
            return False

    def add_color_row(self, expected_index):
        """点击新增按钮，直到出现期望的颜色行"""
        try:
            color_info_list = self.driver.find_element(By.CSS_SELECTOR, ".color-info-list")
        except Exception:
            print("❌ 未找到颜色信息列表，无法新增颜色")
            return False

        current_count = self._count_color_units(color_info_list)
        target_count = expected_index + 1

        if current_count >= target_count:
            print("ℹ️ 颜色行数量已满足要求，无需新增")
            return True

        add_button = self._find_add_color_button(color_info_list)
        if not add_button:
            print("❌ 未找到新增颜色按钮")
            return False

        try:
            add_button.click()
            print("✅ 点击新增颜色按钮")
        except Exception:
            try:
                self.driver.execute_script("arguments[0].click();", add_button)
                print("✅ 使用JavaScript点击新增颜色按钮")
            except Exception as e:
                print(f"❌ 新增颜色按钮点击失败: {e}")
                return False

        rows = self._wait_for_color_row_count(color_info_list, target_count, previous_count=current_count)
        if rows:
            print(f"✅ 新增颜色行成功，当前行数: {len(rows)}")
            return True

        print("⚠️ 新增颜色后未检测到新的颜色行，尝试重新定位容器")
        try:
            color_info_list = self.driver.find_element(By.CSS_SELECTOR, ".color-info-list")
            rows = self._wait_for_color_row_count(color_info_list, target_count, previous_count=current_count)
            if rows:
                print(f"✅ 重新定位后检测到新颜色行，当前行数: {len(rows)}")
                return True
        except Exception as e:
            print(f"❌ 重新定位颜色信息列表失败: {e}")

        print("❌ 新增颜色后仍未检测到新的颜色行")
        return False

    def _find_add_color_button(self, color_info_list):
        """在颜色区域查找新增按钮"""
        selectors = [
            ".add-btn",
            ".pro-button.add-btn",
            "button.add-btn",
            ".color-info-add button",
            ".color-info-add .jx-button",
            ".color-info-list .jx-button--text",
            ".color-info-list .jx-button--ghost",
            ".color-info-list .jx-button",
        ]

        for selector in selectors:
            try:
                buttons = color_info_list.find_elements(By.CSS_SELECTOR, selector)
                for button in buttons:
                    if button.is_displayed():
                        print(f"🔍 通过选择器 '{selector}' 找到新增按钮")
                        return button
            except Exception:
                continue

        # 在父级节点中通过文本匹配“新增”
        search_containers = [color_info_list]
        try:
            parent = color_info_list.find_element(By.XPATH, "..")
            search_containers.append(parent)
            grand_parent = parent.find_element(By.XPATH, "..")
            search_containers.append(grand_parent)
        except Exception:
            pass

        for container in search_containers:
            try:
                add_elements = container.find_elements(By.XPATH, ".//*[contains(normalize-space(text()), '新增')]")
                for element in add_elements:
                    if element.is_displayed():
                        print("🔍 通过文本匹配找到新增元素")
                        return element
            except Exception:
                continue

        return None

    def _is_color_row_element(self, element):
        """判断元素是否为有效的颜色行"""
        try:
            if element.get_attribute("class") and "pro-virtual-table__row" in element.get_attribute("class"):
                return True
        except Exception:
            pass

        try:
            cascaders = element.find_elements(By.CSS_SELECTOR, ".jx-cascader")
            if any(c.is_displayed() for c in cascaders):
                return True
        except Exception:
            pass

        try:
            inputs = element.find_elements(By.CSS_SELECTOR, "input")
            if any(inp.is_displayed() for inp in inputs):
                return True
        except Exception:
            pass

        return False

    def _wait_for_color_row_count(self, color_info_list, target_count, previous_count=0, timeout=6):
        """等待颜色行数量达到目标"""
        end_time = time.time() + timeout
        while time.time() < end_time:
            rows = self._get_color_units(color_info_list)
            if len(rows) >= target_count and len(rows) > previous_count:
                return rows
            time.sleep(0.5)
        return []

    def _count_color_units(self, color_info_list):
        try:
            return len(self._get_color_units(color_info_list))
        except Exception:
            return 0

    def _get_color_units(self, color_info_list):
        """获取颜色输入单元（行或 cascader 组件）"""
        try:
            rows = color_info_list.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row")
            rows = [r for r in rows if r.is_displayed()]
            rows = [r for r in rows if self._is_color_row_element(r)]
            if rows:
                return rows
        except Exception:
            pass

        try:
            direct_children = color_info_list.find_elements(By.XPATH, "./*")
            rows = [c for c in direct_children if c.is_displayed() and self._is_color_row_element(c)]
            if rows:
                return rows
        except Exception:
            pass

        selectors = [
            ".color-info-item",
            ".color-info",
            ".color-item",
            ".color-info-row",
            ".sku-attr-item",
            ".jx-flex",
            "li",
        ]

        for selector in selectors:
            try:
                elements = color_info_list.find_elements(By.CSS_SELECTOR, selector)
            except Exception:
                continue
            rows = [el for el in elements if el.is_displayed() and self._is_color_row_element(el)]
            if rows:
                return rows

        try:
            cascaders = [c for c in color_info_list.find_elements(By.CSS_SELECTOR, ".jx-cascader") if c.is_displayed()]
            if cascaders:
                return cascaders
        except Exception:
            pass

        return []

    def handle_package_info(self, product_data):
        """处理包装类型信息"""
        try:
            print("📦 开始处理包装类型信息...")

            # 1. 处理外包装形状
            package_shape = product_data.get('外包装形状', '')
            if package_shape:
                print(f"📐 处理外包装形状: {package_shape}")
                if self.select_package_shape(package_shape):
                    print("✅ 外包装形状选择成功")
                else:
                    print("⚠️ 外包装形状选择失败")
            else:
                print("⚠️ 未找到外包装形状信息")

            # 2. 处理外包装类型
            package_type = product_data.get('外包装类型', '')
            if package_type:
                print(f"📦 处理外包装类型: {package_type}")
                if self.select_package_type(package_type):
                    print("✅ 外包装类型选择成功")
                else:
                    print("⚠️ 外包装类型选择失败")
            else:
                print("⚠️ 未找到外包装类型信息")

            # 3. 处理外包装图片
            print("🖼️ 处理外包装图片...")
            if self.handle_package_images():
                print("✅ 外包装图片处理成功")
            else:
                print("⚠️ 外包装图片处理失败")

            return True

        except Exception as e:
            print(f"❌ 处理包装类型信息失败: {e}")
            return False

    def select_package_shape(self, shape_value):
        """选择外包装形状"""
        try:
            print(f"📐 选择外包装形状: {shape_value}")

            # 1. 首先找到包装信息区域
            package_section = self.find_package_info_section()
            if not package_section:
                print("❌ 未找到包装信息区域")
                return False

            # 2. 在包装信息区域内查找外包装形状
            shape_input = self.find_package_field_input(package_section, "外包装形状")
            if not shape_input:
                print("❌ 未找到外包装形状输入框")
                return False

            # 3. 点击输入框并输入值
            return self.fill_package_field(shape_input, shape_value, "外包装形状")

        except Exception as e:
            print(f"❌ 选择外包装形状失败: {e}")
            return False

    def find_package_info_section(self):
        """查找包装信息区域"""
        try:
            print("🔍 查找包装信息区域...")

            # 查找 class=scroll-menu-pane 下的包装信息标签
            scroll_panes = self.driver.find_elements(By.CSS_SELECTOR, ".scroll-menu-pane")

            for pane in scroll_panes:
                try:
                    # 查找包装信息标签
                    labels = pane.find_elements(By.CSS_SELECTOR, ".scroll-menu-pane__label")
                    for label in labels:
                        if "包装信息" in label.text:
                            print("✅ 找到包装信息标签")
                            # 查找包含包装字段的区域
                            try:
                                # 查找包装信息标签的父级元素
                                parent = label.find_element(By.XPATH, "..")
                                # 查找同级的div元素（包含字段的区域）
                                sibling_divs = parent.find_elements(By.XPATH, "./following-sibling::div")
                                print(f"   🔍 找到 {len(sibling_divs)} 个同级div")

                                # 检查每个同级div，找到包含包装字段的那个
                                for i, div in enumerate(sibling_divs):
                                    try:
                                        div_text = div.text[:200]  # 只检查前200个字符
                                        print(f"     div{i+1}内容: '{div_text}...'")

                                        # 检查是否包含包装相关的关键词
                                        package_keywords = ['外包装形状', '外包装类型', '外包装图片', '形状', '类型']
                                        if any(keyword in div_text for keyword in package_keywords):
                                            print(f"✅ 找到包含包装字段的div{i+1}")
                                            return div
                                    except:
                                        continue

                                # 如果没找到包含包装字段的div，在整个pane中查找
                                print("⚠️ 未找到包含包装字段的同级div，在整个pane中查找包装字段")

                                # 在整个pane中查找包装字段
                                all_text = pane.text
                                if any(keyword in all_text for keyword in ['外包装形状', '外包装类型', '外包装图片']):
                                    print("✅ 在整个pane中找到包装字段，返回整个pane")
                                    return pane
                                else:
                                    print("❌ 整个pane中都没有找到包装字段")
                                    return None
                            except:
                                print("⚠️ 查找同级div失败，返回整个pane")
                                return pane
                except:
                    continue

            print("❌ 未找到包装信息区域")
            return None

        except Exception as e:
            print(f"❌ 查找包装信息区域失败: {e}")
            return None

    def find_package_field_input(self, package_section, field_name):
        """在包装信息字段区域内查找指定字段的输入框"""
        try:
            print(f"🔍 在包装信息字段区域查找 {field_name} 输入框...")

            # 添加调试信息：显示字段区域的内容
            try:
                section_text = package_section.text[:300]  # 显示前300个字符
                print(f"   📋 字段区域内容预览: '{section_text}...'")
            except:
                pass

            # 直接在字段区域中查找包含字段名的标签
            field_labels = package_section.find_elements(By.XPATH, f".//*[contains(text(), '{field_name}')]")
            print(f"   🔍 找到 {len(field_labels)} 个包含'{field_name}'的元素")

            if not field_labels:
                # 如果没找到完全匹配的，尝试部分匹配
                partial_matches = []
                if "外包装形状" in field_name:
                    partial_matches = package_section.find_elements(By.XPATH, ".//*[contains(text(), '形状')]")
                elif "外包装类型" in field_name:
                    partial_matches = package_section.find_elements(By.XPATH, ".//*[contains(text(), '类型')]")
                elif "外包装图片" in field_name:
                    partial_matches = package_section.find_elements(By.XPATH, ".//*[contains(text(), '图片')]")

                if partial_matches:
                    print(f"   🔍 通过部分匹配找到 {len(partial_matches)} 个元素")
                    field_labels = partial_matches

            for i, label in enumerate(field_labels):
                try:
                    label_text = label.text.strip()
                    print(f"   📝 标签{i+1}: '{label_text}'")

                    # 查找标签旁边的输入框
                    # 方法1: 查找标签所在行的输入框
                    try:
                        # 查找标签的父级容器（通常是一行）
                        row_container = label
                        for level in range(3):  # 向上查找3层
                            row_container = row_container.find_element(By.XPATH, "..")
                            # 在这一层查找输入框
                            inputs = row_container.find_elements(By.CSS_SELECTOR, "input, .jx-select, [class*='select']")

                            print(f"     在第{level+1}层父级中找到 {len(inputs)} 个输入元素")

                            for j, input_elem in enumerate(inputs):
                                try:
                                    if input_elem.is_displayed() and input_elem.is_enabled():
                                        input_class = input_elem.get_attribute("class") or ""
                                        input_tag = input_elem.tag_name
                                        print(f"       输入元素{j+1}: tag={input_tag}, class='{input_class[:50]}...'")

                                        # 检查这个输入框是否在标签附近
                                        try:
                                            label_location = label.location
                                            input_location = input_elem.location
                                            # 如果输入框在标签的右侧或下方不远处
                                            if (input_location['x'] >= label_location['x'] - 50 and
                                                abs(input_location['y'] - label_location['y']) < 100):
                                                print(f"✅ 找到 {field_name} 输入框 (位置匹配)")
                                                return input_elem
                                        except:
                                            # 如果无法获取位置，就返回第一个找到的
                                            print(f"✅ 找到 {field_name} 输入框 (第{level+1}层)")
                                            return input_elem
                                except:
                                    continue
                    except:
                        pass

                    # 方法2: 查找后续兄弟元素中的输入框
                    try:
                        siblings = label.find_elements(By.XPATH, "./following-sibling::*//input | ./following-sibling::*//*[contains(@class, 'jx-select')]")
                        print(f"     在兄弟元素中找到 {len(siblings)} 个输入元素")

                        for j, input_elem in enumerate(siblings):
                            try:
                                if input_elem.is_displayed() and input_elem.is_enabled():
                                    input_class = input_elem.get_attribute("class") or ""
                                    input_tag = input_elem.tag_name
                                    print(f"       兄弟输入元素{j+1}: tag={input_tag}, class='{input_class[:50]}...'")
                                    print(f"✅ 找到 {field_name} 输入框 (兄弟元素)")
                                    return input_elem
                            except:
                                continue
                    except:
                        pass

                except Exception as e:
                    print(f"     处理标签{i+1}失败: {e}")
                    continue

            print(f"❌ 未找到 {field_name} 输入框")
            return None

        except Exception as e:
            print(f"❌ 查找 {field_name} 输入框失败: {e}")
            return None

    def fill_package_field(self, input_elem, value, field_name):
        """填写包装字段并选择选项 - 使用成功的方法"""
        try:
            print(f"📝 填写 {field_name}: {value}")

            # 使用成功验证的包装字段选择方法
            result = self.test_single_package_field(field_name, value)

            if result:
                print(f"✅ {field_name} 选择成功")
                return True
            else:
                print(f"⚠️ {field_name} 自动选择失败，建议手动处理")
                print(f"💡 建议：请手动在界面上选择 {field_name} = '{value}'")
                return True  # 继续流程，不中断

        except Exception as e:
            print(f"❌ 填写 {field_name} 失败: {e}")
            print(f"💡 建议：请手动在界面上选择 {field_name} = '{value}'")
            return True  # 即使失败也继续流程

    def try_direct_package_selection(self, target_value, field_name):
        """尝试直接在页面上查找并点击包装选项"""
        try:
            print(f"     🔍 在页面上查找包装选项: '{target_value}'")

            # 包装相关关键词
            if "形状" in field_name:
                keywords = ['不规则', '规则', '长方体', '圆柱体', '球形', '椭圆']
            else:  # 包装类型
                keywords = ['软包装', '硬包装', '纸箱', '塑料', '泡沫', '木箱']

            # 详细调试：查找页面上所有文本元素
            print(f"     🔍 调试：查找页面上所有包含关键词的文本...")
            all_elements = self.driver.find_elements(By.XPATH, "//*[text()]")
            package_elements = []

            for elem in all_elements:
                try:
                    if elem.is_displayed():
                        elem_text = elem.text.strip()
                        if elem_text and any(keyword in elem_text for keyword in keywords + [target_value]):
                            package_elements.append((elem, elem_text))
                except:
                    continue

            print(f"     📋 找到 {len(package_elements)} 个包含包装关键词的元素")

            # 显示前10个元素的详细信息
            for i, (elem, text) in enumerate(package_elements[:10]):
                try:
                    tag = elem.tag_name
                    classes = elem.get_attribute("class") or ""
                    print(f"       元素{i+1}: '{text}' (tag={tag}, class='{classes[:30]}...')")
                except:
                    continue

            # 尝试点击匹配的元素
            for i, (elem, text) in enumerate(package_elements):
                try:
                    # 检查是否匹配目标值
                    if target_value.lower() in text.lower():
                        print(f"       🎯 尝试点击匹配元素: '{text}'")

                        # 滚动到元素可见
                        self.driver.execute_script("arguments[0].scrollIntoView(true);", elem)
                        time.sleep(0.5)

                        try:
                            elem.click()
                            print(f"     ✅ 成功点击包装选项: '{text}'")
                            return True
                        except:
                            try:
                                self.driver.execute_script("arguments[0].click();", elem)
                                print(f"     ✅ 通过JavaScript点击包装选项: '{text}'")
                                return True
                            except:
                                print(f"       ❌ 点击失败: '{text}'")
                                continue

                except Exception as e:
                    continue

            print(f"     ❌ 未找到可点击的包装选项")
            return False

        except Exception as e:
            print(f"     ❌ 直接查找包装选项失败: {e}")
            return False

    def debug_package_info_area(self):
        """调试包装信息区域 - 按照用户建议的方法查找"""
        try:
            print("🔍 开始调试包装信息区域...")

            # 第一步：查找 class=scroll-menu-wrap 的div
            print("   📋 第一步：查找 class=scroll-menu-wrap 的div...")
            scroll_menu_wraps = self.driver.find_elements(By.CSS_SELECTOR, ".scroll-menu-wrap")
            print(f"   📊 找到 {len(scroll_menu_wraps)} 个 scroll-menu-wrap 元素")

            if not scroll_menu_wraps:
                print("   ❌ 未找到 scroll-menu-wrap 元素")
                return False

            # 使用第一个 scroll-menu-wrap
            scroll_menu_wrap = scroll_menu_wraps[0]
            print("   ✅ 使用第一个 scroll-menu-wrap 元素")

            # 第二步：查找其下的所有直接子div
            print("   📋 第二步：查找 scroll-menu-wrap 下的所有直接子div...")
            child_divs = scroll_menu_wrap.find_elements(By.XPATH, "./div")
            print(f"   📊 找到 {len(child_divs)} 个直接子div")

            # 显示前10个div的信息
            for i, div in enumerate(child_divs[:10]):
                try:
                    div_class = div.get_attribute("class") or ""
                    div_text = div.text.strip()[:50] if div.text else ""
                    print(f"     div{i+1}: class='{div_class}', text='{div_text}...'")
                except:
                    print(f"     div{i+1}: 无法获取信息")

            # 第三步：检查第五个div（如果存在）
            if len(child_divs) >= 5:
                print("   📋 第三步：检查第五个div的内容...")
                fifth_div = child_divs[4]  # 索引从0开始，第五个是索引4

                try:
                    fifth_div_class = fifth_div.get_attribute("class") or ""
                    fifth_div_text = fifth_div.text.strip()
                    print(f"   🎯 第五个div: class='{fifth_div_class}'")
                    print(f"   📝 第五个div内容长度: {len(fifth_div_text)} 字符")

                    # 检查是否包含包装相关内容
                    package_keywords = ['包装信息', '外包装形状', '外包装类型', '外包装图片']
                    has_package_content = any(keyword in fifth_div_text for keyword in package_keywords)

                    if has_package_content:
                        print("   ✅ 第五个div包含包装相关内容！")
                        print("   📋 详细内容:")

                        # 分段显示内容
                        lines = fifth_div_text.split('\n')
                        for i, line in enumerate(lines[:20]):  # 显示前20行
                            if line.strip():
                                print(f"     行{i+1}: {line.strip()}")

                        if len(lines) > 20:
                            print(f"     ... 还有 {len(lines) - 20} 行内容")

                        # 查找包装相关的输入框和选择器
                        print("   🔍 在第五个div中查找包装相关的输入框...")
                        package_selects = fifth_div.find_elements(By.CSS_SELECTOR, ".jx-select")
                        print(f"   📊 找到 {len(package_selects)} 个选择器")

                        for i, select in enumerate(package_selects[:5]):
                            try:
                                # 获取选择器的上下文
                                parent = select.find_element(By.XPATH, "..")
                                context = parent.text.strip()[:100]
                                select_class = select.get_attribute("class") or ""
                                print(f"     选择器{i+1}: class='{select_class[:50]}...', 上下文='{context}...'")
                            except:
                                print(f"     选择器{i+1}: 无法获取详细信息")

                        return True
                    else:
                        print("   ⚠️ 第五个div不包含包装相关内容")
                        print("   📝 内容预览:")
                        preview = fifth_div_text[:200] if fifth_div_text else "无文本内容"
                        print(f"     {preview}...")

                except Exception as e:
                    print(f"   ❌ 检查第五个div失败: {e}")
            else:
                print(f"   ❌ 子div数量不足，只有 {len(child_divs)} 个，需要至少5个")

            # 第四步：如果第五个div不是包装信息，尝试查找其他div
            print("   📋 第四步：在所有子div中查找包装信息...")
            for i, div in enumerate(child_divs):
                try:
                    div_text = div.text.strip()
                    if '包装信息' in div_text or '外包装' in div_text:
                        print(f"   ✅ 在第{i+1}个div中找到包装信息！")
                        print(f"   📝 内容预览: {div_text[:200]}...")
                        return True
                except:
                    continue

            print("   ❌ 在所有子div中都未找到包装信息")
            return False

        except Exception as e:
            print(f"❌ 调试包装信息区域失败: {e}")
            return False

    def test_package_field_selection(self, product_data):
        """测试包装字段选择功能"""
        try:
            print("🔍 开始测试包装字段选择功能...")

            # 获取包装信息
            package_shape = product_data.get('外包装形状', '不规则')
            package_type = product_data.get('外包装类型', '软包装+硬物')

            print(f"   📦 外包装形状: {package_shape}")
            print(f"   📦 外包装类型: {package_type}")

            # 先测试外包装类型选择（可能需要先选择类型才能激活形状选项）
            print("   🔍 测试外包装类型选择...")
            type_result = self.test_single_package_field('外包装类型', package_type)

            if type_result:
                print("   ✅ 外包装类型选择成功，等待页面更新...")
                time.sleep(2)  # 等待页面状态更新

                # 再测试外包装形状选择
                print("   🔍 测试外包装形状选择...")
                shape_result = self.test_single_package_field('外包装形状', package_shape)

                return shape_result and type_result
            else:
                print("   ❌ 外包装类型选择失败，跳过形状选择")
                return False

        except Exception as e:
            print(f"❌ 测试包装字段选择失败: {e}")
            return False

    def test_single_package_field(self, field_name, target_value):
        """测试单个包装字段的选择"""
        try:
            print(f"     🎯 测试 {field_name} = '{target_value}'")

            # 在包装信息区域查找对应的字段
            package_area = self.find_package_info_area()
            if not package_area:
                print(f"     ❌ 未找到包装信息区域")
                return False

            print(f"     ✅ 找到包装信息区域")

            # 查找字段标签
            field_labels = package_area.find_elements(By.XPATH, f"//*[contains(text(), '{field_name}')]")
            if not field_labels:
                print(f"     ❌ 未找到 {field_name} 标签")
                return False

            print(f"     ✅ 找到 {field_name} 标签")

            # 查找包装信息区域内的所有选择器
            all_selects = package_area.find_elements(By.CSS_SELECTOR, ".jx-select")
            print(f"     📊 包装区域内找到 {len(all_selects)} 个选择器")

            # 根据字段名确定选择器索引
            if "形状" in field_name:
                select_index = 0  # 第一个选择器是外包装形状
            elif "类型" in field_name:
                select_index = 1  # 第二个选择器是外包装类型
            else:
                select_index = 0

            if select_index < len(all_selects):
                select = all_selects[select_index]
                print(f"     ✅ 使用第{select_index + 1}个选择器作为 {field_name}")

                # 滚动到选择器可见
                self.driver.execute_script("arguments[0].scrollIntoView(true);", select)
                time.sleep(0.5)

                # 点击选择器
                try:
                    select.click()
                    print(f"     ✅ 点击 {field_name} 选择器")
                except:
                    self.driver.execute_script("arguments[0].click();", select)
                    print(f"     ✅ 通过JavaScript点击 {field_name} 选择器")

                time.sleep(2)

                # 查找下拉选项
                print(f"     🔍 查找 {field_name} 的下拉选项...")
                options = self.find_package_dropdown_options(field_name, target_value)

                if options:
                    print(f"     ✅ 找到 {len(options)} 个选项")

                    # 显示所有选项
                    for i, opt in enumerate(options):
                        try:
                            opt_text = opt.text.strip()
                            print(f"       选项{i+1}: '{opt_text}'")
                        except:
                            print(f"       选项{i+1}: 无法获取文本")

                    # 尝试选择匹配的选项
                    for opt in options:
                        try:
                            opt_text = opt.text.strip()
                            if target_value.lower() in opt_text.lower():
                                try:
                                    opt.click()
                                    print(f"     ✅ 成功选择匹配选项: '{opt_text}'")
                                    return True
                                except:
                                    self.driver.execute_script("arguments[0].click();", opt)
                                    print(f"     ✅ 通过JavaScript选择匹配选项: '{opt_text}'")
                                    return True
                        except:
                            continue

                    # 如果没有匹配的，选择第一个
                    if options:
                        try:
                            first_opt = options[0]
                            first_opt_text = first_opt.text.strip()
                            try:
                                first_opt.click()
                                print(f"     ⚠️ 选择第一个选项: '{first_opt_text}'")
                                return True
                            except:
                                self.driver.execute_script("arguments[0].click();", first_opt)
                                print(f"     ⚠️ 通过JavaScript选择第一个选项: '{first_opt_text}'")
                                return True
                        except Exception as e:
                            print(f"     ❌ 选择第一个选项失败: {e}")
                else:
                    print(f"     ❌ 未找到 {field_name} 的下拉选项")
            else:
                print(f"     ❌ 选择器索引 {select_index} 超出范围，只有 {len(all_selects)} 个选择器")

            print(f"     ❌ {field_name} 选择失败")
            return False

        except Exception as e:
            print(f"     ❌ 测试 {field_name} 失败: {e}")
            return False

    def find_package_dropdown_options(self, field_name, target_value):
        """查找包装字段的下拉选项"""
        try:
            print(f"       🔍 查找 {field_name} 的下拉选项...")

            # 查找所有可见的下拉框
            dropdowns = self.driver.find_elements(By.CSS_SELECTOR, ".jx-select-dropdown, .jx-popper")
            visible_dropdowns = [d for d in dropdowns if d.is_displayed()]

            print(f"       📊 找到 {len(visible_dropdowns)} 个可见下拉框")

            for i, dropdown in enumerate(visible_dropdowns):
                try:
                    dropdown_text = dropdown.text.lower()

                    # 包装关键词
                    package_keywords = ['不规则', '规则', '长方体', '圆柱体', '软包装', '硬包装', '纸箱', '塑料']

                    if any(keyword in dropdown_text for keyword in package_keywords):
                        print(f"       ✅ 下拉框{i+1}包含包装关键词")

                        # 查找选项
                        options = dropdown.find_elements(By.CSS_SELECTOR, "li, .jx-option, [role='option']")
                        if options:
                            print(f"       📊 找到 {len(options)} 个选项")

                            # 显示选项内容
                            for j, opt in enumerate(options[:5]):
                                try:
                                    opt_text = opt.text.strip()
                                    print(f"         选项{j+1}: '{opt_text}'")
                                except:
                                    continue

                            return options
                    else:
                        print(f"       ⚠️ 下拉框{i+1}不包含包装关键词: '{dropdown_text[:50]}...'")

                except Exception as e:
                    print(f"       ❌ 检查下拉框{i+1}失败: {e}")
                    continue

            print(f"       ❌ 未找到包装相关的下拉选项")
            return []

        except Exception as e:
            print(f"       ❌ 查找下拉选项失败: {e}")
            return []

    def debug_package_image_upload(self):
        """调试外包装图片上传功能"""
        try:
            print("🔍 开始调试外包装图片上传功能...")

            # 第一步：找到包装信息区域
            print("   📋 第一步：找到包装信息区域...")
            package_area = self.find_package_info_area()
            if not package_area:
                print("   ❌ 未找到包装信息区域")
                return False

            print("   ✅ 找到包装信息区域")

            # 第二步：在包装信息区域查找外包装图片相关元素
            print("   📋 第二步：查找外包装图片相关元素...")
            package_text = package_area.text

            if "外包装图片" not in package_text:
                print("   ❌ 包装信息区域不包含外包装图片")
                return False

            print("   ✅ 包装信息区域包含外包装图片")

            # 第三步：查找上传图片按钮
            print("   📋 第三步：查找上传图片按钮...")

            # 更精确地查找真正的上传按钮
            upload_buttons = []

            # 方法1：查找button标签
            buttons = package_area.find_elements(By.TAG_NAME, "button")
            for btn in buttons:
                try:
                    btn_text = btn.text.strip()
                    if "上传图片" in btn_text and len(btn_text) < 20:  # 避免长文本
                        upload_buttons.append(btn)
                except:
                    continue

            # 方法2：查找具有上传相关class的元素
            upload_classes = [
                "[class*='upload-btn']",
                "[class*='upload-button']",
                "[class*='btn-upload']",
                ".upload-trigger",
                ".upload-area"
            ]

            for selector in upload_classes:
                try:
                    elements = package_area.find_elements(By.CSS_SELECTOR, selector)
                    upload_buttons.extend(elements)
                except:
                    continue

            # 方法3：查找包含"上传图片"的短文本元素（排除长提示文本）
            xpath_selectors = [
                ".//button[contains(text(), '上传图片')]",
                ".//div[contains(text(), '上传图片') and string-length(text()) < 20]",
                ".//span[contains(text(), '上传图片') and string-length(text()) < 20]"
            ]

            for xpath in xpath_selectors:
                try:
                    elements = package_area.find_elements(By.XPATH, xpath)
                    upload_buttons.extend(elements)
                except:
                    continue

            # 去重
            unique_buttons = []
            for btn in upload_buttons:
                if btn not in unique_buttons:
                    unique_buttons.append(btn)

            upload_buttons = unique_buttons
            print(f"   📊 找到 {len(upload_buttons)} 个候选上传按钮")

            # 显示找到的上传按钮详细信息
            for i, btn in enumerate(upload_buttons[:10]):
                try:
                    btn_text = btn.text.strip()
                    btn_tag = btn.tag_name
                    btn_class = btn.get_attribute("class") or ""
                    btn_clickable = btn.is_enabled() and btn.is_displayed()
                    print(f"     按钮{i+1}: tag={btn_tag}, text='{btn_text[:30]}...', clickable={btn_clickable}")
                    print(f"              class='{btn_class[:50]}...'")
                except:
                    print(f"     按钮{i+1}: 无法获取详细信息")

            # 第四步：尝试点击上传图片按钮
            print("   📋 第四步：尝试点击上传图片按钮...")

            upload_clicked = False
            for i, btn in enumerate(upload_buttons):
                try:
                    if btn.is_displayed() and btn.is_enabled():
                        print(f"     🎯 尝试点击按钮{i+1}...")

                        # 滚动到按钮可见
                        self.driver.execute_script("arguments[0].scrollIntoView(true);", btn)
                        time.sleep(0.5)

                        # 点击按钮
                        try:
                            btn.click()
                            print(f"     ✅ 成功点击按钮{i+1}")
                            upload_clicked = True
                            break
                        except:
                            self.driver.execute_script("arguments[0].click();", btn)
                            print(f"     ✅ 通过JavaScript点击按钮{i+1}")
                            upload_clicked = True
                            break

                except Exception as e:
                    print(f"     ❌ 点击按钮{i+1}失败: {e}")
                    continue

            if not upload_clicked:
                print("   ❌ 未能点击任何上传图片按钮")
                return False

            # 第五步：等待并查找下拉菜单
            print("   📋 第五步：等待并查找下拉菜单...")
            time.sleep(2)

            # 查找下拉菜单
            dropdown_selectors = [
                ".jx-popper",
                ".jx-dropdown-menu",
                "[class*='dropdown']",
                "[class*='menu']",
                "[class*='popover']"
            ]

            dropdown_found = False
            for selector in dropdown_selectors:
                try:
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    visible_dropdowns = [d for d in dropdowns if d.is_displayed()]

                    print(f"     {selector}: 找到 {len(visible_dropdowns)} 个可见下拉框")

                    for j, dropdown in enumerate(visible_dropdowns):
                        try:
                            dropdown_text = dropdown.text.strip()
                            print(f"       下拉框{j+1}内容: '{dropdown_text[:100]}...'")

                            # 检查是否包含"选择空间图片"
                            if "选择空间图片" in dropdown_text:
                                print(f"       ✅ 下拉框{j+1}包含'选择空间图片'！")

                                # 查找"选择空间图片"按钮
                                space_image_buttons = dropdown.find_elements(By.XPATH, ".//*[contains(text(), '选择空间图片')]")

                                print(f"       📊 找到 {len(space_image_buttons)} 个'选择空间图片'按钮")

                                for k, space_btn in enumerate(space_image_buttons):
                                    try:
                                        space_btn_text = space_btn.text.strip()
                                        space_btn_tag = space_btn.tag_name
                                        space_btn_class = space_btn.get_attribute("class") or ""
                                        print(f"         空间图片按钮{k+1}: tag={space_btn_tag}, text='{space_btn_text}', class='{space_btn_class[:30]}...'")

                                        # 尝试点击"选择空间图片"按钮
                                        print(f"         🎯 尝试点击'选择空间图片'按钮{k+1}...")

                                        try:
                                            space_btn.click()
                                            print(f"         ✅ 成功点击'选择空间图片'按钮{k+1}")
                                            dropdown_found = True

                                            # 等待空间图片选择界面出现
                                            print("   📋 第六步：等待空间图片选择界面...")
                                            time.sleep(3)

                                            # 查找空间图片选择界面
                                            return self.debug_space_image_selection()

                                        except:
                                            self.driver.execute_script("arguments[0].click();", space_btn)
                                            print(f"         ✅ 通过JavaScript点击'选择空间图片'按钮{k+1}")
                                            dropdown_found = True

                                            # 等待空间图片选择界面出现
                                            print("   📋 第六步：等待空间图片选择界面...")
                                            time.sleep(3)

                                            # 查找空间图片选择界面
                                            return self.debug_space_image_selection()

                                    except Exception as e:
                                        print(f"         ❌ 处理空间图片按钮{k+1}失败: {e}")
                                        continue

                                if dropdown_found:
                                    break

                        except Exception as e:
                            print(f"       ❌ 检查下拉框{j+1}失败: {e}")
                            continue

                    if dropdown_found:
                        break

                except Exception as e:
                    print(f"     {selector} 查找失败: {e}")
                    continue

            if not dropdown_found:
                print("   ❌ 未找到包含'选择空间图片'的下拉菜单")
                return False

            return True

        except Exception as e:
            print(f"❌ 调试外包装图片上传失败: {e}")
            return False

    def debug_space_image_selection(self):
        """调试空间图片选择界面 - 完整操作流程"""
        try:
            print("   🔍 调试空间图片选择界面...")

            # 第一步：查找空间图片选择对话框
            print("     📋 第一步：查找空间图片选择对话框...")
            dialog = self.find_space_image_dialog()
            if not dialog:
                print("     ❌ 未找到空间图片选择对话框")
                return False

            print("     ✅ 找到空间图片选择对话框")

            # 第二步：在名称输入框输入"包装"
            print("     📋 第二步：在名称输入框输入'包装'...")
            if not self.input_search_keyword(dialog, "包装"):
                print("     ❌ 输入搜索关键词失败")
                return False

            print("     ✅ 成功输入搜索关键词'包装'")

            # 第三步：点击搜索按钮
            print("     📋 第三步：点击搜索按钮...")
            if not self.click_search_button(dialog):
                print("     ❌ 点击搜索按钮失败")
                return False

            print("     ✅ 成功点击搜索按钮")

            # 第四步：等待搜索结果加载
            print("     📋 第四步：等待搜索结果加载...")
            time.sleep(3)

            # 第五步：全选搜索出来的图片
            print("     📋 第五步：全选搜索出来的图片...")
            selected_count = self.select_all_search_images(dialog)
            if selected_count == 0:
                print("     ❌ 未找到或选择图片")
                return False

            print(f"     ✅ 成功选择 {selected_count} 张图片")

            # 第六步：点击footer的确定按钮
            print("     📋 第六步：点击footer的确定按钮...")
            if not self.click_confirm_button_in_dialog(dialog):
                print("     ❌ 点击确定按钮失败")
                return False

            print("     ✅ 成功点击确定按钮")

            # 第七步：等待对话框关闭
            print("     📋 第七步：等待对话框关闭...")
            time.sleep(2)

            print("   ✅ 空间图片选择完整流程执行成功")
            return True

        except Exception as e:
            print(f"   ❌ 调试空间图片选择界面失败: {e}")
            return False

    def find_space_image_dialog(self):
        """查找空间图片选择对话框"""
        try:
            dialog_selectors = [
                ".jx-dialog",
                ".jx-modal",
                "[class*='dialog']",
                "[class*='modal']",
                "[role='dialog']"
            ]

            for selector in dialog_selectors:
                try:
                    dialogs = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    visible_dialogs = [d for d in dialogs if d.is_displayed()]

                    for dialog in visible_dialogs:
                        try:
                            dialog_text = dialog.text.strip()
                            if "选择空间图片" in dialog_text:
                                return dialog
                        except:
                            continue

                except:
                    continue

            return None

        except:
            return None

    def input_search_keyword(self, dialog, keyword):
        """在名称输入框输入搜索关键词"""
        try:
            # 查找名称输入框
            input_selectors = [
                "input[placeholder*='名称']",
                "input[placeholder*='搜索']",
                "input[name*='name']",
                ".search-input input",
                "input"
            ]

            for selector in input_selectors:
                try:
                    inputs = dialog.find_elements(By.CSS_SELECTOR, selector)
                    for input_elem in inputs:
                        try:
                            if input_elem.is_displayed() and input_elem.is_enabled():
                                # 检查是否是名称输入框
                                placeholder = input_elem.get_attribute("placeholder") or ""
                                if "名称" in placeholder or not placeholder:
                                    print(f"       🎯 找到名称输入框: placeholder='{placeholder}'")

                                    # 清空并输入关键词
                                    input_elem.clear()
                                    input_elem.send_keys(keyword)

                                    # 验证输入
                                    input_value = input_elem.get_attribute("value")
                                    print(f"       ✅ 输入验证: '{input_value}'")

                                    return True
                        except:
                            continue
                except:
                    continue

            print("       ❌ 未找到名称输入框")
            return False

        except Exception as e:
            print(f"       ❌ 输入搜索关键词失败: {e}")
            return False

    def click_search_button(self, dialog):
        """点击搜索按钮"""
        try:
            print("       🔍 详细查找搜索按钮...")

            # 首先查找所有按钮元素
            all_buttons = dialog.find_elements(By.TAG_NAME, "button")
            print(f"       📊 对话框中总共找到 {len(all_buttons)} 个button元素")

            search_buttons = []

            # 检查每个按钮
            for i, btn in enumerate(all_buttons):
                try:
                    if btn.is_displayed():
                        btn_text = btn.text.strip()
                        btn_class = btn.get_attribute("class") or ""
                        print(f"       🔍 按钮{i+1}: text='{btn_text}', class='{btn_class[:50]}...'")

                        if "搜索" in btn_text:
                            search_buttons.append(btn)
                            print(f"       ✅ 找到搜索按钮{i+1}: '{btn_text}'")
                except Exception as e:
                    print(f"       ❌ 检查按钮{i+1}失败: {e}")
                    continue

            # 如果没找到包含"搜索"文本的按钮，查找其他可能的搜索按钮
            if not search_buttons:
                print("       🔍 未找到包含'搜索'文本的按钮，查找其他可能的搜索按钮...")

                # 查找可能的搜索按钮（通过class或位置）
                possible_search_selectors = [
                    "button[class*='primary']",  # 主要按钮通常是搜索按钮
                    "button[class*='search']",
                    "button[class*='btn-primary']",
                    ".search-btn",
                    "[class*='search-button']"
                ]

                for selector in possible_search_selectors:
                    try:
                        buttons = dialog.find_elements(By.CSS_SELECTOR, selector)
                        for btn in buttons:
                            if btn.is_displayed() and btn not in search_buttons:
                                search_buttons.append(btn)
                                btn_text = btn.text.strip()
                                btn_class = btn.get_attribute("class") or ""
                                print(f"       ✅ 找到可能的搜索按钮: text='{btn_text}', class='{btn_class[:50]}...'")
                    except:
                        continue

            print(f"       📊 总共找到 {len(search_buttons)} 个搜索按钮候选")

            # 尝试点击搜索按钮
            for i, btn in enumerate(search_buttons):
                try:
                    if btn.is_displayed() and btn.is_enabled():
                        btn_text = btn.text.strip()
                        print(f"       🎯 尝试点击搜索按钮{i+1}: '{btn_text}'")

                        try:
                            btn.click()
                            print(f"       ✅ 成功点击搜索按钮{i+1}")
                            return True
                        except:
                            self.driver.execute_script("arguments[0].click();", btn)
                            print(f"       ✅ 通过JavaScript点击搜索按钮{i+1}")
                            return True

                except Exception as e:
                    print(f"       ❌ 点击搜索按钮{i+1}失败: {e}")
                    continue

            # 如果还是没找到，尝试查找输入框附近的按钮
            print("       🔍 尝试查找输入框附近的按钮...")
            try:
                name_input = dialog.find_element(By.CSS_SELECTOR, "input[placeholder*='名称']")
                parent = name_input.find_element(By.XPATH, "./..")
                nearby_buttons = parent.find_elements(By.TAG_NAME, "button")

                print(f"       📊 输入框附近找到 {len(nearby_buttons)} 个按钮")

                for i, btn in enumerate(nearby_buttons):
                    try:
                        if btn.is_displayed() and btn.is_enabled():
                            btn_text = btn.text.strip()
                            btn_class = btn.get_attribute("class") or ""
                            print(f"       🎯 尝试点击附近按钮{i+1}: text='{btn_text}', class='{btn_class[:30]}...'")

                            try:
                                btn.click()
                                print(f"       ✅ 成功点击附近按钮{i+1}")
                                return True
                            except:
                                self.driver.execute_script("arguments[0].click();", btn)
                                print(f"       ✅ 通过JavaScript点击附近按钮{i+1}")
                                return True
                    except Exception as e:
                        print(f"       ❌ 点击附近按钮{i+1}失败: {e}")
                        continue

            except Exception as e:
                print(f"       ❌ 查找输入框附近按钮失败: {e}")

            print("       ❌ 未能点击任何搜索按钮")
            return False

        except Exception as e:
            print(f"       ❌ 点击搜索按钮失败: {e}")
            return False

    def select_all_search_images(self, dialog):
        """全选搜索出来的图片"""
        try:
            print("       🔍 详细查找图片元素...")

            # 首先查找图片容器区域
            image_container_selectors = [
                ".picture-list",
                ".image-list",
                "[class*='picture-list']",
                "[class*='image-list']",
                ".content"
            ]

            image_container = None
            for selector in image_container_selectors:
                try:
                    containers = dialog.find_elements(By.CSS_SELECTOR, selector)
                    for container in containers:
                        if container.is_displayed():
                            container_text = container.text
                            if "包装图片" in container_text or len(container.find_elements(By.TAG_NAME, "img")) > 0:
                                image_container = container
                                print(f"       ✅ 找到图片容器: {selector}")
                                break
                    if image_container:
                        break
                except:
                    continue

            if not image_container:
                image_container = dialog
                print("       📋 使用整个对话框作为图片容器")

            # 查找所有图片项目（包括图片和其容器）
            image_item_selectors = [
                ".picture-item",
                "[class*='picture-item']",
                "[class*='image-item']",
                ".item",
                "li",
                "div[class*='item']"
            ]

            image_items = []

            for selector in image_item_selectors:
                try:
                    items = image_container.find_elements(By.CSS_SELECTOR, selector)
                    for item in items:
                        if item.is_displayed():
                            # 检查是否包含图片
                            imgs = item.find_elements(By.TAG_NAME, "img")
                            if imgs:
                                # 检查是否是包装相关图片
                                item_text = item.text
                                is_package_related = False

                                for img in imgs:
                                    img_src = img.get_attribute("src") or ""
                                    img_alt = img.get_attribute("alt") or ""
                                    if "包装" in img_src or "包装" in img_alt or "包装" in item_text:
                                        is_package_related = True
                                        break

                                if is_package_related:
                                    image_items.append(item)
                                    print(f"       ✅ 找到包装图片项目: '{item_text[:30]}...'")

                    if image_items:
                        break

                except Exception as e:
                    print(f"       ❌ 查找图片项目失败 ({selector}): {e}")
                    continue

            # 如果没找到相关图片，查找所有图片项目
            if not image_items:
                print("       🔍 未找到相关图片，查找所有图片项目...")

                # 等待更长时间确保图片加载完成
                time.sleep(3)

                # 尝试更多的选择器
                all_image_selectors = [
                    ".picture-item",
                    "[class*='picture-item']",
                    "[class*='image-item']",
                    ".item",
                    "li",
                    "div[class*='item']",
                    "img",  # 直接查找img标签
                    "[class*='photo']",
                    "[class*='pic']"
                ]

                for selector in all_image_selectors:
                    try:
                        items = image_container.find_elements(By.CSS_SELECTOR, selector)
                        print(f"       🔍 使用选择器 {selector} 找到 {len(items)} 个元素")

                        for item in items:
                            if item.is_displayed():
                                # 检查是否包含图片或是图片本身
                                is_image_item = False
                                item_text = ""

                                try:
                                    if item.tag_name == "img":
                                        # 如果是img标签，检查父容器
                                        parent = item.find_element(By.XPATH, "./..")
                                        image_items.append(parent)
                                        item_text = item.get_attribute("alt") or item.get_attribute("src") or ""
                                        is_image_item = True
                                    else:
                                        # 检查是否包含图片
                                        imgs = item.find_elements(By.TAG_NAME, "img")
                                        if imgs:
                                            image_items.append(item)
                                            item_text = item.text
                                            is_image_item = True

                                    if is_image_item:
                                        print(f"       📋 找到图片项目: '{item_text[:50]}...'")

                                except Exception as e:
                                    print(f"       ⚠️ 检查图片项目失败: {e}")
                                    continue

                        if image_items:
                            print(f"       ✅ 使用选择器 {selector} 找到 {len(image_items)} 个图片项目")
                            break

                    except Exception as e:
                        print(f"       ❌ 选择器 {selector} 查找失败: {e}")
                        continue

            print(f"       📊 总共找到 {len(image_items)} 个图片项目")

            if not image_items:
                print("       ❌ 未找到任何图片项目")
                return 0

            # 选择所有图片项目
            selected_count = 0
            for i, item in enumerate(image_items):
                try:
                    print(f"       🎯 尝试选择图片项目{i+1}")

                    # 检查是否已经被选中
                    item_class = item.get_attribute("class") or ""
                    is_selected = "selected" in item_class or "active" in item_class

                    if is_selected:
                        print(f"       ℹ️ 图片项目{i+1}已经被选中")
                        selected_count += 1
                        continue

                    # 尝试点击选择
                    try:
                        # 先尝试直接点击
                        item.click()
                        selected_count += 1
                        print(f"       ✅ 成功选择图片项目{i+1}")
                    except:
                        try:
                            # 尝试JavaScript点击
                            self.driver.execute_script("arguments[0].click();", item)
                            selected_count += 1
                            print(f"       ✅ 通过JavaScript选择图片项目{i+1}")
                        except:
                            # 尝试点击图片本身
                            imgs = item.find_elements(By.TAG_NAME, "img")
                            if imgs:
                                imgs[0].click()
                                selected_count += 1
                                print(f"       ✅ 通过点击图片选择项目{i+1}")
                            else:
                                print(f"       ❌ 无法选择图片项目{i+1}")
                                continue

                    time.sleep(0.3)  # 短暂等待选择生效

                except Exception as e:
                    print(f"       ❌ 选择图片项目{i+1}失败: {e}")
                    continue

            print(f"       ✅ 总共选择了 {selected_count} 张图片")

            # 验证选择结果
            time.sleep(1)
            try:
                selected_items = image_container.find_elements(By.CSS_SELECTOR, "[class*='selected'], [class*='active']")
                print(f"       📊 验证: 当前有 {len(selected_items)} 个项目被选中")
            except:
                pass

            return selected_count

        except Exception as e:
            print(f"       ❌ 选择图片失败: {e}")
            return 0

    def click_confirm_button_in_dialog(self, dialog):
        """点击footer的确定按钮"""
        try:
            print("       🔍 详细查找确定按钮...")

            # 首先查找对话框中的所有按钮
            all_buttons = dialog.find_elements(By.TAG_NAME, "button")
            print(f"       📊 对话框中总共找到 {len(all_buttons)} 个button元素")

            confirm_buttons = []

            # 检查每个按钮
            for i, btn in enumerate(all_buttons):
                try:
                    if btn.is_displayed():
                        btn_text = btn.text.strip()
                        btn_class = btn.get_attribute("class") or ""
                        print(f"       🔍 按钮{i+1}: text='{btn_text}', class='{btn_class[:50]}...'")

                        if "确定" in btn_text:
                            confirm_buttons.append(btn)
                            print(f"       ✅ 找到确定按钮{i+1}: '{btn_text}'")
                except Exception as e:
                    print(f"       ❌ 检查按钮{i+1}失败: {e}")
                    continue

            print(f"       📊 总共找到 {len(confirm_buttons)} 个确定按钮候选")

            # 尝试点击确定按钮
            for i, btn in enumerate(confirm_buttons):
                try:
                    if btn.is_displayed() and btn.is_enabled():
                        btn_text = btn.text.strip()
                        print(f"       🎯 尝试点击确定按钮{i+1}: '{btn_text}'")

                        try:
                            btn.click()
                            print(f"       ✅ 成功点击确定按钮{i+1}")
                            return True
                        except:
                            self.driver.execute_script("arguments[0].click();", btn)
                            print(f"       ✅ 通过JavaScript点击确定按钮{i+1}")
                            return True

                except Exception as e:
                    print(f"       ❌ 点击确定按钮{i+1}失败: {e}")
                    continue

            print("       ❌ 未能点击任何确定按钮")
            return False

        except Exception as e:
            print(f"       ❌ 点击确定按钮失败: {e}")
            return False

    def click_confirm_button(self):
        """点击确定按钮（无参数版本）"""
        try:
            print("🔍 查找并点击确定按钮...")

            # 使用XPath查找包含"确定"文本的按钮
            xpath_selectors = [
                "//button[contains(text(), '确定')]",
                "//div[contains(text(), '确定') and contains(@class, 'btn')]",
                "//span[contains(text(), '确定')]"
            ]

            confirm_buttons = []

            for xpath in xpath_selectors:
                try:
                    buttons = self.driver.find_elements(By.XPATH, xpath)
                    confirm_buttons.extend(buttons)
                except:
                    continue

            print(f"📊 找到 {len(confirm_buttons)} 个确定按钮")

            for i, btn in enumerate(confirm_buttons):
                try:
                    if btn.is_displayed() and btn.is_enabled():
                        btn_text = btn.text.strip()
                        print(f"🎯 尝试点击确定按钮{i+1}: '{btn_text}'")

                        try:
                            btn.click()
                            print(f"✅ 成功点击确定按钮{i+1}")
                            return True
                        except:
                            self.driver.execute_script("arguments[0].click();", btn)
                            print(f"✅ 通过JavaScript点击确定按钮{i+1}")
                            return True

                except Exception as e:
                    print(f"❌ 点击确定按钮{i+1}失败: {e}")
                    continue

            print("❌ 未能点击任何确定按钮")
            return False

        except Exception as e:
            print(f"❌ 点击确定按钮失败: {e}")
            return False

    def find_package_info_area(self):
        """查找包装信息区域 - 使用成功的方法"""
        try:
            # 使用与debug_package_info_area相同的逻辑
            scroll_menu_wraps = self.driver.find_elements(By.CSS_SELECTOR, ".scroll-menu-wrap")
            if not scroll_menu_wraps:
                return None

            scroll_menu_wrap = scroll_menu_wraps[0]
            child_divs = scroll_menu_wrap.find_elements(By.XPATH, "./div")

            # 检查第五个div（索引4）
            if len(child_divs) >= 5:
                fifth_div = child_divs[4]
                fifth_div_text = fifth_div.text.strip()

                # 检查是否包含包装相关内容
                if '包装信息' in fifth_div_text and '外包装' in fifth_div_text:
                    return fifth_div

            # 如果第五个div不是，查找其他包含包装信息的div
            for div in child_divs:
                try:
                    div_text = div.text.strip()
                    if '包装信息' in div_text and '外包装' in div_text:
                        return div
                except:
                    continue

            return None
        except:
            return None

    def wait_and_find_package_dropdown(self, select_container, field_name, target_value):
        """等待包装下拉框出现并查找选项"""
        try:
            print(f"     ⏳ 等待 {field_name} 下拉框出现...")

            # 等待下拉框出现
            for attempt in range(5):
                time.sleep(1)
                print(f"       尝试 {attempt + 1}/5...")

                # 查找包装相关的下拉框
                dropdowns = self.driver.find_elements(By.CSS_SELECTOR, ".jx-select-dropdown, .jx-popper")

                for dropdown in dropdowns:
                    if dropdown.is_displayed():
                        dropdown_text = dropdown.text.lower()

                        # 包装关键词
                        package_keywords = ['不规则', '规则', '长方体', '圆柱体', '软包装', '硬包装', '纸箱', '塑料']

                        if any(keyword in dropdown_text for keyword in package_keywords):
                            print(f"       ✅ 找到包装下拉框")

                            # 查找选项
                            options = dropdown.find_elements(By.CSS_SELECTOR, "li, .jx-option")
                            if options:
                                valid_options = []
                                for opt in options:
                                    try:
                                        opt_text = opt.text.strip()
                                        if opt_text and any(keyword in opt_text for keyword in package_keywords):
                                            valid_options.append(opt)
                                            print(f"         包装选项: '{opt_text}'")
                                    except:
                                        continue

                                if valid_options:
                                    return valid_options

                # 如果没找到，再次点击
                if attempt < 4:
                    try:
                        self.driver.execute_script("arguments[0].click();", select_container)
                        print(f"       🔄 第{attempt + 1}次重新点击")
                    except:
                        pass

            print(f"     ❌ 未找到包装下拉框")
            return []

        except Exception as e:
            print(f"     ❌ 等待包装下拉框失败: {e}")
            return []

    def select_package_option(self, options, target_value, field_name):
        """选择包装选项"""
        try:
            print(f"     🎯 选择 {field_name} 选项...")

            # 查找匹配的选项
            matched_option = None
            for opt in options:
                try:
                    opt_text = opt.text.strip()
                    if target_value.lower() in opt_text.lower() or opt_text.lower() in target_value.lower():
                        matched_option = opt
                        print(f"     ✅ 找到匹配选项: '{opt_text}'")
                        break
                except:
                    continue

            # 如果没找到匹配的，选择第一个
            if not matched_option and options:
                matched_option = options[0]
                print(f"     ⚠️ 未找到匹配选项，选择第一个: '{matched_option.text.strip()}'")

            if matched_option:
                try:
                    matched_option.click()
                    print(f"     ✅ 成功选择: '{matched_option.text.strip()}'")
                    return True
                except:
                    self.driver.execute_script("arguments[0].click();", matched_option)
                    print(f"     ✅ 通过JavaScript选择: '{matched_option.text.strip()}'")
                    return True
            else:
                print(f"     ❌ 没有可选择的选项")
                return False

        except Exception as e:
            print(f"     ❌ 选择包装选项失败: {e}")
            return False

    def wait_and_find_dropdown_options(self, select_container, field_name, target_value):
        """等待下拉框出现并查找选项"""
        try:
            print(f"   ⏳ 等待 {field_name} 下拉框出现...")

            # 使用显式等待，等待包含包装关键词的下拉框出现
            from selenium.webdriver.support.ui import WebDriverWait
            from selenium.webdriver.support import expected_conditions as EC

            # 包装相关关键词
            package_keywords = ['不规则', '规则', '长方体', '圆柱体', '软包装', '硬包装']

            # 等待最多10秒，每0.5秒检查一次
            wait = WebDriverWait(self.driver, 10)

            for attempt in range(10):
                try:
                    print(f"     尝试 {attempt + 1}/10 查找包装下拉框...")

                    # 查找所有可见的下拉框
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, ".jx-select-dropdown, .jx-popper")
                    visible_dropdowns = [d for d in dropdowns if d.is_displayed()]

                    print(f"       找到 {len(visible_dropdowns)} 个可见下拉框")

                    for i, dropdown in enumerate(visible_dropdowns):
                        try:
                            dropdown_text = dropdown.text.lower()

                            # 检查是否包含包装关键词
                            has_package_keywords = any(keyword in dropdown_text for keyword in package_keywords)

                            if has_package_keywords:
                                print(f"       ✅ 找到包含包装关键词的下拉框{i+1}")
                                print(f"       下拉框内容: '{dropdown_text[:100]}...'")

                                # 查找这个下拉框中的选项
                                options = self.find_options_in_dropdown(dropdown, field_name)
                                if options:
                                    return options
                            else:
                                # 显示前3个下拉框的内容用于调试
                                if i < 3:
                                    print(f"       下拉框{i+1}内容: '{dropdown_text[:50]}...'")

                        except Exception as e:
                            print(f"       检查下拉框{i+1}失败: {e}")
                            continue

                    # 如果没找到，再次点击并等待
                    if attempt < 9:
                        try:
                            self.driver.execute_script("arguments[0].click();", select_container)
                            print(f"     🔄 第{attempt + 1}次重新点击")
                            time.sleep(0.5)
                        except:
                            pass

                except Exception as e:
                    print(f"     尝试{attempt + 1}失败: {e}")
                    time.sleep(0.5)
                    continue

            print(f"   ❌ 10次尝试后仍未找到包装下拉框")
            return []

        except Exception as e:
            print(f"   ❌ 等待下拉框失败: {e}")
            return []

    def find_dropdown_near_element(self, select_container, field_name):
        """查找靠近指定元素的下拉框"""
        try:
            print(f"     🔍 查找 {field_name} 附近的下拉框...")

            # 获取select_container的位置
            container_location = select_container.location
            container_size = select_container.size
            print(f"       选择器位置: x={container_location['x']}, y={container_location['y']}")
            print(f"       选择器尺寸: w={container_size['width']}, h={container_size['height']}")

            # 查找所有可能的下拉框
            dropdown_selectors = [
                ".jx-select-dropdown",
                ".jx-popper",
                "[class*='dropdown']"
            ]

            for selector in dropdown_selectors:
                try:
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"       {selector}: 找到 {len(dropdowns)} 个下拉框")

                    for i, dropdown in enumerate(dropdowns):
                        try:
                            if not dropdown.is_displayed():
                                continue

                            # 获取下拉框位置
                            dropdown_location = dropdown.location
                            dropdown_size = dropdown.size

                            # 检查下拉框是否在选择器附近（通常在下方）
                            x_diff = abs(dropdown_location['x'] - container_location['x'])
                            y_diff = dropdown_location['y'] - container_location['y']

                            print(f"         下拉框{i+1}: x={dropdown_location['x']}, y={dropdown_location['y']}")
                            print(f"         位置差异: x_diff={x_diff}, y_diff={y_diff}")

                            # 下拉框应该在选择器下方且x坐标相近
                            # 放宽条件：x坐标差异在200以内，y坐标在下方300以内
                            if x_diff <= 200 and 0 <= y_diff <= 300:
                                print(f"         ✅ 找到位置匹配的下拉框")

                                # 查找这个下拉框中的选项
                                options = self.find_options_in_dropdown(dropdown, field_name)
                                if options:
                                    return options
                            else:
                                print(f"         ⚠️ 位置不匹配，跳过")

                        except Exception as e:
                            print(f"         下拉框{i+1}检查失败: {e}")
                            continue

                except Exception as e:
                    print(f"       {selector} 查找失败: {e}")
                    continue

            print(f"     ❌ 未找到位置匹配的下拉框")
            return []

        except Exception as e:
            print(f"     ❌ 查找附近下拉框失败: {e}")
            return []

    def find_options_in_dropdown(self, dropdown, field_name):
        """在指定的下拉框中查找选项"""
        try:
            print(f"         🔍 在下拉框中查找选项...")

            # 获取下拉框内容预览
            dropdown_text = dropdown.text.strip()
            print(f"         下拉框内容: '{dropdown_text[:100]}...'")

            # 查找选项元素
            option_selectors = [
                "li",
                ".jx-option",
                "[role='option']",
                "div[class*='option']",
                "span"
            ]

            for opt_selector in option_selectors:
                options = dropdown.find_elements(By.CSS_SELECTOR, opt_selector)
                if options:
                    print(f"           找到 {len(options)} 个选项 ({opt_selector})")

                    # 检查选项内容
                    valid_options = []
                    for i, opt in enumerate(options):
                        try:
                            opt_text = opt.text.strip()
                            if opt_text and len(opt_text) > 0 and len(opt_text) < 50:
                                valid_options.append(opt)
                                if i < 5:  # 显示前5个
                                    print(f"             选项{i+1}: '{opt_text}'")
                        except:
                            continue

                    if valid_options:
                        # 检查是否是包装相关的选项
                        sample_texts = [opt.text.strip() for opt in valid_options[:3]]
                        sample_text = ' '.join(sample_texts)

                        # 包装相关关键词
                        package_keywords = ['规则', '不规则', '长方体', '圆柱体', '软包装', '硬包装', '纸箱', '塑料', '请选择']
                        # 无关关键词
                        irrelevant_keywords = ['店铺', '条/页', '已发布', '未发布', '已标记', '未标记', '语言', '英语', '德语']

                        has_package_keywords = any(keyword in sample_text for keyword in package_keywords)
                        has_irrelevant_keywords = any(keyword in sample_text for keyword in irrelevant_keywords)

                        print(f"           样本文本: '{sample_text}'")
                        print(f"           包装关键词匹配: {has_package_keywords}")
                        print(f"           无关关键词匹配: {has_irrelevant_keywords}")

                        # 对于包装字段，必须包含包装关键词才认为是正确的下拉框
                        if has_package_keywords:
                            print(f"         ✅ 找到包装相关选项")
                            return valid_options
                        else:
                            print(f"         ⚠️ 跳过无关选项: '{sample_text}'")

            print(f"         ❌ 未找到有效选项")
            return []

        except Exception as e:
            print(f"         ❌ 查找选项失败: {e}")
            return []

    def find_package_options_on_page(self, field_name, target_value):
        """在整个页面上查找包装选项"""
        try:
            print(f"     🔍 在整个页面查找包装选项...")

            # 包装相关关键词
            if "形状" in field_name:
                keywords = ['不规则', '规则', '长方体', '圆柱体', '球形', '椭圆']
            else:  # 包装类型
                keywords = ['软包装', '硬包装', '纸箱', '塑料', '泡沫', '木箱']

            # 查找包含这些关键词的元素
            all_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '不规则') or contains(text(), '规则') or contains(text(), '长方体') or contains(text(), '圆柱体') or contains(text(), '软包装') or contains(text(), '硬包装')]")

            print(f"       找到 {len(all_elements)} 个包含包装关键词的元素")

            package_options = []
            for i, elem in enumerate(all_elements):
                try:
                    if elem.is_displayed():
                        elem_text = elem.text.strip()
                        if any(keyword in elem_text for keyword in keywords):
                            package_options.append(elem)
                            if i < 10:  # 显示前10个
                                print(f"         包装选项{i+1}: '{elem_text}'")
                except:
                    continue

            if package_options:
                print(f"     ✅ 找到 {len(package_options)} 个包装选项")
                return package_options
            else:
                print(f"     ❌ 未找到包装选项")
                return []

        except Exception as e:
            print(f"     ❌ 在页面查找包装选项失败: {e}")
            return []

    def find_dropdown_options(self, field_name, target_value):
        """查找下拉选项"""
        try:
            print(f"   🔍 查找 {field_name} 的下拉选项...")

            # 查找所有可能的下拉框
            dropdown_selectors = [
                ".jx-select-dropdown",
                ".jx-popper",
                "[class*='dropdown']",
                "[class*='popper']"
            ]

            print(f"     🔍 调试：查找所有下拉框...")
            all_dropdowns = []

            for selector in dropdown_selectors:
                try:
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"       {selector}: 找到 {len(dropdowns)} 个元素")

                    for i, dropdown in enumerate(dropdowns):
                        try:
                            is_displayed = dropdown.is_displayed()
                            dropdown_class = dropdown.get_attribute("class") or ""
                            print(f"         下拉框{i+1}: displayed={is_displayed}, class='{dropdown_class[:50]}...'")

                            if is_displayed:
                                all_dropdowns.append((dropdown, selector))
                        except:
                            continue

                except Exception as e:
                    print(f"       {selector} 查找失败: {e}")
                    continue

            print(f"     ✅ 总共找到 {len(all_dropdowns)} 个可见的下拉框")

            # 检查每个可见的下拉框
            for dropdown, selector in all_dropdowns:
                try:
                    print(f"     🔍 检查下拉框 ({selector})...")

                    # 获取下拉框的文本内容
                    dropdown_text = dropdown.text.strip()
                    print(f"       下拉框内容预览: '{dropdown_text[:100]}...'")

                    # 查找选项
                    option_selectors = [
                        "li",
                        ".jx-option",
                        "[role='option']",
                        "div[class*='option']",
                        "span"
                    ]

                    for opt_selector in option_selectors:
                        options = dropdown.find_elements(By.CSS_SELECTOR, opt_selector)
                        if options:
                            print(f"         找到 {len(options)} 个选项 ({opt_selector})")

                            # 检查选项内容
                            valid_options = []
                            for i, opt in enumerate(options):
                                try:
                                    opt_text = opt.text.strip()
                                    if opt_text and len(opt_text) > 0 and len(opt_text) < 50:
                                        valid_options.append(opt)
                                        if i < 8:  # 显示前8个
                                            print(f"           选项{i+1}: '{opt_text}'")
                                except:
                                    continue

                            if valid_options:
                                # 检查是否是包装相关的选项
                                sample_texts = [opt.text.strip() for opt in valid_options[:5]]
                                sample_text = ' '.join(sample_texts)

                                # 包装相关关键词
                                package_keywords = ['规则', '不规则', '长方体', '圆柱体', '软包装', '硬包装', '纸箱', '塑料', '请选择']
                                # 无关关键词
                                irrelevant_keywords = ['店铺', '条/页', '已发布', '未发布', '已标记', '未标记', '语言', '英语', '德语']

                                has_package_keywords = any(keyword in sample_text for keyword in package_keywords)
                                has_irrelevant_keywords = any(keyword in sample_text for keyword in irrelevant_keywords)

                                print(f"         样本文本: '{sample_text}'")
                                print(f"         包装关键词匹配: {has_package_keywords}")
                                print(f"         无关关键词匹配: {has_irrelevant_keywords}")

                                if has_package_keywords or (not has_irrelevant_keywords and len(valid_options) <= 10):
                                    print(f"       ✅ 找到包装相关选项")
                                    return valid_options
                                else:
                                    print(f"       ⚠️ 跳过无关选项")

                except Exception as e:
                    print(f"     检查下拉框失败: {e}")
                    continue

            print(f"   ❌ 未找到有效的下拉选项")
            return []

        except Exception as e:
            print(f"   ❌ 查找下拉选项失败: {e}")
            return []



    def find_matching_option(self, options, target_value, field_name):
        """在选项列表中查找匹配的选项"""
        try:
            print(f"   🔍 在 {len(options)} 个选项中查找匹配 '{target_value}' 的选项...")

            # 清理目标值
            target_clean = target_value.strip().lower()

            # 首先打印前10个选项的内容以便调试
            print(f"   📋 前10个选项内容:")
            valid_options = []
            for i, option in enumerate(options[:20]):  # 检查前20个
                try:
                    option_text = option.text.strip()
                    option_value = option.get_attribute("value") or ""
                    option_title = option.get_attribute("title") or ""
                    option_label = option.get_attribute("label") or ""
                    option_data_value = option.get_attribute("data-value") or ""
                    option_data_label = option.get_attribute("data-label") or ""
                    option_innerHTML = ""

                    # 尝试获取innerHTML
                    try:
                        option_innerHTML = self.driver.execute_script("return arguments[0].innerHTML;", option).strip()
                    except:
                        pass

                    # 尝试获取子元素的文本
                    child_texts = []
                    try:
                        children = option.find_elements(By.CSS_SELECTOR, "*")
                        for child in children[:3]:  # 只检查前3个子元素
                            child_text = child.text.strip()
                            if child_text:
                                child_texts.append(child_text)
                    except:
                        pass

                    # 收集所有可能的文本内容
                    all_texts = [option_text, option_value, option_title, option_label,
                                option_data_value, option_data_label, option_innerHTML] + child_texts

                    # 过滤掉空值和无意义的值
                    meaningful_texts = [t for t in all_texts if t and t != "0" and len(t.strip()) > 0]

                    if meaningful_texts:
                        valid_options.append(option)
                        print(f"     选项{i+1}: text='{option_text}', value='{option_value}', innerHTML='{option_innerHTML[:50]}...', children={child_texts}")

                        if len(valid_options) >= 10:  # 找到10个有效选项就停止
                            break

                except Exception as e:
                    print(f"     选项{i+1}解析失败: {e}")
                    continue

            print(f"   📊 找到 {len(valid_options)} 个有效选项")

            # 在有效选项中进行匹配
            if not valid_options:
                print(f"   ❌ 没有找到有效的选项内容")
                return None

            # 精确匹配
            for option in valid_options:
                try:
                    # 获取所有可能的文本内容
                    all_texts = self.get_option_all_texts(option)

                    for text_info in all_texts:
                        text = text_info['text']
                        source = text_info['source']
                        if text and text.strip().lower() == target_clean:
                            print(f"   ✅ 找到精确匹配: '{text}' (来源: {source})")
                            return option
                except:
                    continue

            # 包含匹配
            for option in valid_options:
                try:
                    option_text = option.text.strip()
                    option_value = option.get_attribute("value") or ""
                    option_title = option.get_attribute("title") or ""

                    # 检查所有可能的文本内容
                    texts_to_check = [option_text, option_value, option_title]
                    for text in texts_to_check:
                        if text and (target_clean in text.lower() or text.lower() in target_clean):
                            print(f"   ✅ 找到包含匹配: '{text}' (在{['text', 'value', 'title'][texts_to_check.index(text)]}中)")
                            return option
                except:
                    continue

            # 部分匹配（关键词匹配）
            import re
            target_words = re.findall(r'\w+', target_clean)
            if target_words:
                for option in valid_options:
                    try:
                        option_text = option.text.strip()
                        option_value = option.get_attribute("value") or ""
                        option_title = option.get_attribute("title") or ""

                        # 检查所有可能的文本内容
                        texts_to_check = [option_text, option_value, option_title]
                        for text in texts_to_check:
                            if text:
                                text_words = re.findall(r'\w+', text.lower())
                                common_words = set(target_words) & set(text_words)
                                if common_words:
                                    print(f"   ✅ 找到关键词匹配: '{text}' (共同词: {common_words})")
                                    return option
                    except:
                        continue

            print(f"   ❌ 未找到匹配 '{target_value}' 的选项")
            return None

        except Exception as e:
            print(f"   ❌ 查找匹配选项失败: {e}")
            return None

    def get_option_all_texts(self, option):
        """获取选项的所有可能文本内容"""
        texts = []
        try:
            # 基本属性
            option_text = option.text.strip()
            if option_text:
                texts.append({'text': option_text, 'source': 'text'})

            option_value = option.get_attribute("value") or ""
            if option_value and option_value != "0":
                texts.append({'text': option_value, 'source': 'value'})

            option_title = option.get_attribute("title") or ""
            if option_title:
                texts.append({'text': option_title, 'source': 'title'})

            option_label = option.get_attribute("label") or ""
            if option_label:
                texts.append({'text': option_label, 'source': 'label'})

            # data属性
            option_data_value = option.get_attribute("data-value") or ""
            if option_data_value:
                texts.append({'text': option_data_value, 'source': 'data-value'})

            option_data_label = option.get_attribute("data-label") or ""
            if option_data_label:
                texts.append({'text': option_data_label, 'source': 'data-label'})

            # innerHTML
            try:
                option_innerHTML = self.driver.execute_script("return arguments[0].innerHTML;", option).strip()
                if option_innerHTML and len(option_innerHTML) < 100:  # 避免太长的HTML
                    # 提取纯文本
                    import re
                    clean_text = re.sub(r'<[^>]+>', '', option_innerHTML).strip()
                    if clean_text:
                        texts.append({'text': clean_text, 'source': 'innerHTML'})
            except:
                pass

            # 子元素文本
            try:
                children = option.find_elements(By.CSS_SELECTOR, "*")
                for i, child in enumerate(children[:3]):  # 只检查前3个子元素
                    child_text = child.text.strip()
                    if child_text:
                        texts.append({'text': child_text, 'source': f'child-{i+1}'})
            except:
                pass

        except Exception as e:
            pass

        return texts

    def find_related_dropdown(self, input_elem, field_name):
        """查找与输入框相关的下拉框"""
        try:
            print(f"   🔍 查找与 {field_name} 输入框相关的下拉框...")

            # 方法1: 通过aria-controls属性
            try:
                controls_id = input_elem.get_attribute("aria-controls")
                if controls_id:
                    dropdown = self.driver.find_element(By.ID, controls_id)
                    if dropdown.is_displayed():
                        print(f"   ✅ 通过aria-controls找到下拉框: {controls_id}")
                        return dropdown
            except:
                pass

            # 方法2: 查找最近出现的下拉框
            try:
                # 查找所有可能的下拉框容器
                dropdown_selectors = [
                    ".jx-select-dropdown",
                    ".jx-popper",
                    "[class*='dropdown']",
                    "[role='listbox']"
                ]

                for selector in dropdown_selectors:
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for dropdown in reversed(dropdowns):  # 从最新的开始检查
                        if dropdown.is_displayed():
                            # 检查下拉框的位置是否接近输入框
                            try:
                                input_location = input_elem.location
                                dropdown_location = dropdown.location

                                # 如果下拉框在输入框附近（垂直距离小于200px）
                                if abs(dropdown_location['y'] - input_location['y']) < 200:
                                    print(f"   ✅ 找到位置接近的下拉框: {selector}")
                                    return dropdown
                            except:
                                # 如果无法获取位置，就返回最新的可见下拉框
                                print(f"   ✅ 找到最新的可见下拉框: {selector}")
                                return dropdown
            except:
                pass

            # 方法3: 查找包含特定内容的下拉框
            try:
                all_dropdowns = self.driver.find_elements(By.CSS_SELECTOR, ".jx-select-dropdown, .jx-popper")
                for dropdown in all_dropdowns:
                    if dropdown.is_displayed():
                        # 检查下拉框内容是否包含包装相关的选项
                        dropdown_text = dropdown.text.lower()
                        package_keywords = ['形状', '类型', '包装', '规则', '不规则', '软包装', '硬包装']
                        if any(keyword in dropdown_text for keyword in package_keywords):
                            print(f"   ✅ 找到包含包装关键词的下拉框")
                            return dropdown
            except:
                pass

            print(f"   ❌ 未找到与 {field_name} 相关的下拉框")
            return None

        except Exception as e:
            print(f"   ❌ 查找相关下拉框失败: {e}")
            return None

    def select_package_type(self, type_value):
        """选择外包装类型"""
        try:
            print(f"📦 选择外包装类型: {type_value}")

            # 1. 首先找到包装信息区域
            package_section = self.find_package_info_section()
            if not package_section:
                print("❌ 未找到包装信息区域")
                return False

            # 2. 在包装信息区域内查找外包装类型
            type_input = self.find_package_field_input(package_section, "外包装类型")
            if not type_input:
                print("❌ 未找到外包装类型输入框")
                return False

            # 3. 点击输入框并输入值
            return self.fill_package_field(type_input, type_value, "外包装类型")

        except Exception as e:
            print(f"❌ 选择外包装类型失败: {e}")
            return False



        except Exception as e:
            print(f"❌ 选择外包装类型失败: {e}")
            return False

    def handle_package_images(self):
        """处理外包装图片"""
        try:
            print("🖼️ 开始处理外包装图片...")

            # 1. 首先找到包装信息区域
            package_section = self.find_package_info_section()
            if not package_section:
                print("❌ 未找到包装信息区域")
                return False

            # 2. 在包装信息区域内查找外包装图片上传按钮
            upload_button = self.find_package_image_upload_button_in_section(package_section)
            if not upload_button:
                print("❌ 未找到外包装图片上传按钮")
                return False

            # 3. 点击上传按钮
            self.driver.execute_script("arguments[0].scrollIntoView(true);", upload_button)
            time.sleep(0.5)
            upload_button.click()
            print("✅ 点击外包装图片上传按钮")
            time.sleep(2)

            # 4. 查找上传弹窗并点击选择空间图片
            time.sleep(2)  # 等待弹窗出现

            # 查找上传弹窗
            upload_popup = None
            popup_selectors = [
                ".jx-popper.is-light.jx-popover",
                ".upload-popup",
                ".image-upload-popup"
            ]

            for selector in popup_selectors:
                popups = self.driver.find_elements(By.CSS_SELECTOR, selector)
                for popup in popups:
                    if popup.is_displayed():
                        upload_popup = popup
                        print(f"✅ 找到上传弹窗: {selector}")
                        break
                if upload_popup:
                    break

            if upload_popup:
                # 直接使用"选择空间图片"按钮进行搜索选择
                try:
                    selector_list = upload_popup.find_element(By.CSS_SELECTOR, ".picture-selector-list")

                    # 查找"选择空间图片"按钮
                    space_upload_button = self.find_space_image_button(selector_list)
                    if space_upload_button and space_upload_button.is_displayed():
                        print(f"🔍 找到选择空间图片按钮: '{space_upload_button.text}'")

                        # 点击"选择空间图片"按钮
                        try:
                            space_upload_button.click()
                            print("✅ 成功点击'选择空间图片'按钮")
                        except:
                            self.driver.execute_script("arguments[0].click();", space_upload_button)
                            print("✅ 使用JavaScript点击'选择空间图片'按钮")

                        time.sleep(3)  # 等待空间图片库加载

                        # 搜索并选择包装图片
                        if self.search_and_select_package_images():
                            print("✅ 包装图片选择成功")
                            return True
                        else:
                            print("⚠️ 包装图片选择失败")
                            return False
                    else:
                        print("❌ 未找到'选择空间图片'按钮")
                        return False

                except Exception as e:
                    print(f"❌ 查找图片选择按钮失败: {e}")
                    return False
            else:
                print("❌ 未找到上传弹窗")
                return False

        except Exception as e:
            print(f"❌ 处理外包装图片失败: {e}")
            return False

    def find_package_image_upload_button_in_section(self, package_section):
        """在包装信息区域内查找外包装图片上传按钮"""
        try:
            print("🔍 在包装信息区域查找外包装图片上传按钮...")

            # 方法1：查找外包装图片标签附近的按钮
            image_labels = package_section.find_elements(By.XPATH, ".//*[contains(text(), '外包装图片')]")
            print(f"   找到 {len(image_labels)} 个外包装图片标签")

            for i, label in enumerate(image_labels):
                try:
                    print(f"   检查标签{i+1}: '{label.text.strip()}'")

                    # 查找标签附近的上传按钮
                    parent = label.find_element(By.XPATH, "..")
                    buttons = parent.find_elements(By.CSS_SELECTOR, "button, .btn, [class*='upload']")

                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            button_text = button.text.strip()
                            if "上传" in button_text or "添加" in button_text or "选择" in button_text:
                                print(f"✅ 找到外包装图片上传按钮: '{button_text}'")
                                return button

                    # 也查找后续兄弟元素中的按钮
                    siblings = label.find_elements(By.XPATH, "./following-sibling::*//button | ./following-sibling::*//*[contains(@class, 'upload')]")
                    for button in siblings:
                        if button.is_displayed() and button.is_enabled():
                            button_text = button.text.strip()
                            print(f"✅ 找到外包装图片上传按钮 (兄弟元素): '{button_text}'")
                            return button

                except Exception as e:
                    print(f"   检查标签{i+1}失败: {e}")
                    continue

            # 方法2：如果没找到，在整个包装区域查找所有上传相关按钮
            print("   方法1未找到，尝试在整个包装区域查找上传按钮...")
            all_buttons = package_section.find_elements(By.CSS_SELECTOR, "button, .btn, [class*='upload'], [class*='add']")
            print(f"   找到 {len(all_buttons)} 个可能的按钮")

            for i, button in enumerate(all_buttons):
                try:
                    if button.is_displayed() and button.is_enabled():
                        button_text = button.text.strip()
                        button_class = button.get_attribute('class') or ''

                        # 检查按钮文本或class是否包含上传相关关键词
                        upload_keywords = ["上传", "添加", "选择", "upload", "add", "select", "+"]
                        if any(keyword in button_text.lower() for keyword in upload_keywords) or \
                           any(keyword in button_class.lower() for keyword in upload_keywords):
                            print(f"✅ 找到可能的上传按钮{i+1}: '{button_text}' (class: {button_class})")
                            return button
                except:
                    continue

            print("❌ 未找到外包装图片上传按钮")
            return None

        except Exception as e:
            print(f"❌ 查找外包装图片上传按钮失败: {e}")
            return None

    def click_local_image_option(self):
        """点击本地图片选项"""
        try:
            print("🔍 查找本地图片选项...")

            # 根据您的描述：class=jx-popper is-light jx-popover下的第一个div下的第二个div
            popover_selector = ".jx-popper.is-light.jx-popover"
            popovers = self.driver.find_elements(By.CSS_SELECTOR, popover_selector)

            for popover in popovers:
                if popover.is_displayed():
                    try:
                        # 获取第一个div下的第二个div
                        first_div = popover.find_element(By.CSS_SELECTOR, "div:first-child")
                        second_div = first_div.find_element(By.CSS_SELECTOR, "div:nth-child(2)")

                        # 点击第二个div
                        second_div.click()
                        print("✅ 点击本地图片选项")
                        time.sleep(2)
                        return True

                    except Exception as e:
                        print(f"⚠️ 尝试popover失败: {e}")
                        continue

            print("❌ 未找到本地图片选项")
            return False

        except Exception as e:
            print(f"❌ 点击本地图片选项失败: {e}")
            return False

    def find_package_image_upload_button(self):
        """查找外包装图片上传按钮"""
        try:
            print("🔍 查找外包装图片上传按钮...")

            # 查找包装图片相关的上传按钮
            button_selectors = [
                "button:contains('上传图片')",
                "button:contains('添加图片')",
                "[class*='package'] button:contains('上传')",
                "[class*='包装'] button:contains('上传')",
                "[class*='外包装'] button:contains('上传')",
                "button[class*='upload']:contains('图片')",
                ".upload-btn:contains('图片')",
                "button:has(.icon-upload)"
            ]

            # 首先尝试通过页面结构定位包装图片区域
            package_sections = self.driver.find_elements(By.XPATH,
                "//*[contains(text(), '外包装图片') or contains(text(), '包装图片')]/ancestor::div[contains(@class, 'form') or contains(@class, 'section')]")

            if package_sections:
                print(f"✅ 找到 {len(package_sections)} 个包装图片区域")

                # 在包装图片区域内查找上传按钮
                for section in package_sections:
                    try:
                        upload_buttons = section.find_elements(By.CSS_SELECTOR,
                            "button, .btn, [class*='upload'], [role='button']")

                        for button in upload_buttons:
                            if button.is_displayed() and button.is_enabled():
                                button_text = button.text.strip()
                                if any(keyword in button_text for keyword in ["上传", "添加", "选择", "+"]):
                                    print(f"✅ 在包装区域找到上传按钮: '{button_text}'")
                                    return button
                    except:
                        continue

            # 如果在特定区域没找到，尝试全局查找
            print("🔍 在全局范围查找上传按钮...")
            for selector in button_selectors:
                try:
                    buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            print(f"✅ 找到上传按钮: {selector}")
                            return button
                except:
                    continue

            print("❌ 未找到外包装图片上传按钮")
            return None

        except Exception as e:
            print(f"❌ 查找外包装图片上传按钮失败: {e}")
            return None

    def find_upload_dropdown_options(self):
        """查找上传下拉框选项"""
        try:
            print("🔍 查找上传下拉框选项...")

            # 等待下拉框出现
            time.sleep(2)

            # 查找下拉框选项
            option_selectors = [
                ".dropdown-menu li",
                ".dropdown-menu a",
                ".menu-item",
                "[class*='dropdown'] [class*='item']",
                "[class*='menu'] [class*='option']",
                ".ant-dropdown-menu-item",
                ".el-dropdown-menu__item",
                # 更通用的选择器
                "ul li",
                ".popover li",
                "[role='menuitem']",
                "[class*='option']",
                # 可能的按钮形式
                "button:contains('本地')",
                "button:contains('图片')",
                "a:contains('本地')",
                "a:contains('图片')"
            ]

            for selector in option_selectors:
                try:
                    if ":contains(" in selector:
                        # 使用XPath处理contains
                        xpath = f"//*[contains(text(), '本地') or contains(text(), '图片') or contains(text(), '选择')]"
                        options = self.driver.find_elements(By.XPATH, xpath)
                    else:
                        options = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    if options:
                        visible_options = [opt for opt in options if opt.is_displayed()]
                        if visible_options:
                            print(f"✅ 找到 {len(visible_options)} 个下拉框选项: {selector}")
                            # 打印选项文本以便调试
                            for i, opt in enumerate(visible_options[:5]):  # 只打印前5个
                                try:
                                    print(f"   选项{i+1}: '{opt.text.strip()}'")
                                except:
                                    pass
                            return visible_options
                except:
                    continue

            print("❌ 未找到下拉框选项")
            return None

        except Exception as e:
            print(f"❌ 查找下拉框选项失败: {e}")
            return None



    def search_and_select_package_images(self):
        """搜索并选择包装图片"""
        try:
            print("🔍 开始搜索并选择包装图片...")

            # 等待页面加载完成
            time.sleep(1)  # 减少等待时间

            # 1. 先调试当前页面状态
            print("📋 调试当前页面状态...")
            self.debug_current_page_for_search()

            # 2. 查找搜索输入框
            search_input = self.find_image_search_input()
            if not search_input:
                print("❌ 未找到图片搜索输入框，尝试其他方法...")
                # 尝试直接选择所有图片
                return self.select_all_available_images()

            # 3. 输入搜索关键词"包装"
            print("📝 清空搜索框并输入关键词...")
            try:
                # 先点击输入框激活
                search_input.click()
                time.sleep(0.5)

                # 清空输入框
                search_input.clear()
                time.sleep(0.5)

                # 输入搜索关键词
                search_input.send_keys("包装")
                print("✅ 输入搜索关键词: 包装")
                time.sleep(0.5)  # 减少等待时间
            except Exception as e:
                print(f"❌ 输入搜索关键词失败: {e}")
                return False

            # 4. 执行搜索
            search_executed = self.execute_search(search_input)
            if not search_executed:
                print("❌ 搜索执行失败")
                return False

            # 等待搜索结果加载
            time.sleep(1)  # 减少等待时间

            # 5. 直接选择搜索到的图片并确认
            if self.select_all_search_results():
                print("✅ 包装图片搜索、选择和确认完成")
                return True
            else:
                print("❌ 选择搜索结果失败")
                return False

        except Exception as e:
            print(f"❌ 搜索并选择包装图片失败: {e}")
            return False

    def debug_current_page_for_search(self):
        """调试当前页面状态，查找搜索相关元素"""
        try:
            print("🔍 调试当前页面搜索相关元素...")

            # 查找所有输入框
            all_inputs = self.driver.find_elements(By.TAG_NAME, "input")
            print(f"   📊 页面总共有 {len(all_inputs)} 个输入框")

            search_input_candidates = []
            for i, inp in enumerate(all_inputs):
                try:
                    if inp.is_displayed():
                        placeholder = inp.get_attribute("placeholder") or ""
                        input_type = inp.get_attribute("type") or ""
                        class_name = inp.get_attribute("class") or ""
                        name = inp.get_attribute("name") or ""
                        value = inp.get_attribute("value") or ""

                        print(f"   输入框{i+1}: type='{input_type}', placeholder='{placeholder}', name='{name}', value='{value}'")
                        print(f"     class='{class_name[:50]}...'")

                        # 如果是搜索相关的输入框，记录下来
                        if any(keyword in placeholder.lower() for keyword in ["搜索", "search", "名称", "关键词"]):
                            search_input_candidates.append((i+1, inp, placeholder))

                except:
                    continue

            print(f"   🎯 找到 {len(search_input_candidates)} 个搜索输入框候选")

            # 查找所有按钮，特别关注搜索输入框附近的按钮
            all_buttons = self.driver.find_elements(By.TAG_NAME, "button")
            print(f"   📊 页面总共有 {len(all_buttons)} 个按钮")

            # 详细分析每个按钮
            for i, btn in enumerate(all_buttons):
                try:
                    if btn.is_displayed():
                        btn_text = btn.text.strip()
                        btn_class = btn.get_attribute("class") or ""
                        btn_title = btn.get_attribute("title") or ""
                        btn_type = btn.get_attribute("type") or ""

                        print(f"   按钮{i+1}: text='{btn_text}', type='{btn_type}', title='{btn_title}'")
                        print(f"     class='{btn_class[:50]}...'")

                        # 特别标记可能的搜索按钮
                        is_search_related = (
                            "搜索" in btn_text or "search" in btn_text.lower() or
                            "search" in btn_class.lower() or "搜索" in btn_title or
                            btn_text == "" or btn_type == "submit"
                        )

                        if is_search_related:
                            print(f"     🎯 可能的搜索按钮！")

                except:
                    continue

            # 如果找到了搜索输入框候选，分析它们附近的按钮
            for idx, (input_num, search_input, placeholder) in enumerate(search_input_candidates):
                try:
                    print(f"\n   🔍 分析搜索输入框{input_num}附近的按钮 (placeholder: '{placeholder}')...")

                    # 查找父容器中的按钮
                    parent = search_input.find_element(By.XPATH, "..")
                    parent_buttons = parent.find_elements(By.TAG_NAME, "button")
                    print(f"     父容器中有 {len(parent_buttons)} 个按钮")

                    for j, btn in enumerate(parent_buttons):
                        if btn.is_displayed():
                            btn_text = btn.text.strip()
                            btn_class = btn.get_attribute("class") or ""
                            print(f"     父容器按钮{j+1}: text='{btn_text}', class='{btn_class[:30]}...'")

                    # 查找兄弟按钮
                    sibling_buttons = search_input.find_elements(By.XPATH, "./following-sibling::button | ./preceding-sibling::button")
                    print(f"     兄弟元素中有 {len(sibling_buttons)} 个按钮")

                    for j, btn in enumerate(sibling_buttons):
                        if btn.is_displayed():
                            btn_text = btn.text.strip()
                            btn_class = btn.get_attribute("class") or ""
                            print(f"     兄弟按钮{j+1}: text='{btn_text}', class='{btn_class[:30]}...'")

                except Exception as e:
                    print(f"     ❌ 分析输入框{input_num}附近按钮失败: {e}")

        except Exception as e:
            print(f"❌ 调试页面状态失败: {e}")

    def execute_search(self, search_input):
        """执行搜索操作"""
        try:
            print("🔍 执行搜索操作...")

            # 直接按回车键搜索，这是最简单可靠的方法
            try:
                from selenium.webdriver.common.keys import Keys
                search_input.send_keys(Keys.RETURN)
                print("✅ 按回车键执行搜索")
                time.sleep(1)  # 等待搜索执行
                return True
            except Exception as e:
                print(f"❌ 按回车键搜索失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 执行搜索失败: {e}")
            return False

    def check_search_results(self):
        """检查搜索结果是否存在"""
        try:
            print("🔍 检查搜索结果...")

            # 查找图片相关元素
            image_selectors = [
                ".image-item",
                ".img-item",
                "[class*='image-card']",
                "[class*='photo-item']",
                "[class*='picture']",
                "img",
                ".thumbnail"
            ]

            total_images = 0
            for selector in image_selectors:
                try:
                    images = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    visible_images = [img for img in images if img.is_displayed()]
                    if visible_images:
                        total_images += len(visible_images)
                        print(f"   通过选择器 '{selector}' 找到 {len(visible_images)} 张图片")
                except:
                    continue

            print(f"📊 总共找到 {total_images} 张可见图片")
            return total_images > 0

        except Exception as e:
            print(f"❌ 检查搜索结果失败: {e}")
            return False

    def select_all_available_images(self):
        """选择所有可用图片（当搜索失败时的备用方案）"""
        try:
            print("🔍 选择所有可用图片...")

            # 查找所有图片元素
            image_selectors = [
                ".image-item",
                ".img-item",
                "[class*='image-card']",
                "[class*='photo-item']",
                "[class*='picture']"
            ]

            selected_count = 0

            for selector in image_selectors:
                try:
                    images = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for image in images:
                        if image.is_displayed():
                            try:
                                image.click()
                                selected_count += 1
                                time.sleep(0.2)
                                print(f"   ✅ 选择图片 {selected_count}")
                            except:
                                continue

                    if selected_count > 0:
                        break  # 如果已经选择了图片，就不用尝试其他选择器了

                except:
                    continue

            print(f"✅ 总共选择了 {selected_count} 张图片")
            return selected_count > 0

        except Exception as e:
            print(f"❌ 选择所有可用图片失败: {e}")
            return False

    def find_image_search_input(self):
        """查找图片搜索输入框"""
        try:
            print("🔍 查找图片搜索输入框...")

            # 等待页面稳定
            time.sleep(1)

            # 扩展的搜索输入框选择器，按优先级排序
            search_selectors = [
                # 最明确的搜索框
                "input[placeholder*='搜索图片']",
                "input[placeholder*='搜索']",
                "input[placeholder*='图片名称']",
                "input[placeholder*='名称']",
                "input[placeholder*='关键词']",

                # 按类名查找
                ".search-input",
                "[class*='search'] input",
                "input[type='search']",
                "input[name*='search']",

                # 框架特定的输入框
                ".jx-input input",
                ".ant-input",
                ".el-input input",

                # 通用输入框（最后尝试）
                "input[class*='input']",
                "input[type='text']"
            ]

            print(f"   尝试 {len(search_selectors)} 种选择器...")

            # 存储所有找到的候选输入框
            candidates = []

            for i, selector in enumerate(search_selectors):
                try:
                    inputs = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"   选择器{i+1} '{selector}': 找到 {len(inputs)} 个输入框")

                    for j, input_elem in enumerate(inputs):
                        if input_elem.is_displayed() and input_elem.is_enabled():
                            placeholder = input_elem.get_attribute("placeholder") or ""
                            class_name = input_elem.get_attribute("class") or ""
                            name = input_elem.get_attribute("name") or ""

                            print(f"     输入框{j+1}: placeholder='{placeholder}', class='{class_name[:30]}...', name='{name}'")

                            # 计算匹配度分数
                            score = 0
                            search_keywords = ["搜索", "search", "名称", "关键词", "图片"]

                            for keyword in search_keywords:
                                if keyword in placeholder.lower():
                                    score += 10
                                if keyword in class_name.lower():
                                    score += 5
                                if keyword in name.lower():
                                    score += 3

                            candidates.append({
                                "element": input_elem,
                                "score": score,
                                "placeholder": placeholder,
                                "selector": selector
                            })

                except Exception as e:
                    print(f"   选择器{i+1}失败: {e}")
                    continue

            # 按分数排序，选择最佳候选
            if candidates:
                candidates.sort(key=lambda x: x["score"], reverse=True)
                best_candidate = candidates[0]

                print(f"✅ 选择最佳搜索输入框: {best_candidate['selector']}")
                print(f"   placeholder: '{best_candidate['placeholder']}', 分数: {best_candidate['score']}")

                return best_candidate["element"]

            # 如果没找到任何候选，尝试查找页面中第一个可用的文本输入框
            print("   未找到明确的搜索框，尝试使用第一个可用文本输入框...")
            try:
                all_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input")
                for input_elem in all_inputs:
                    if input_elem.is_displayed() and input_elem.is_enabled():
                        input_type = input_elem.get_attribute("type") or "text"
                        if input_type in ["text", "search", ""]:
                            placeholder = input_elem.get_attribute("placeholder") or ""
                            print(f"✅ 使用第一个可用文本输入框 (placeholder: '{placeholder}')")
                            return input_elem
            except:
                pass

            print("❌ 未找到任何可用的搜索输入框")
            return None

        except Exception as e:
            print(f"❌ 查找搜索输入框失败: {e}")
            return None

    def select_all_search_results(self):
        """选择所有搜索结果 - 专门针对外包装图片的DOM结构"""
        try:
            print("🔍 选择搜索结果中的图片...")

            # 等待搜索结果加载
            time.sleep(1)

            selected_count = 0
            picture_wrapper = None
            dialog_container = None

            # 1. 先找到 aria-label="选择空间图片" 且 class=jx-overlay-dialog 的容器
            try:
                dialog_container = self.driver.find_element(By.CSS_SELECTOR,
                    "div[aria-label='选择空间图片'].jx-overlay-dialog")
                print("✅ 找到选择空间图片对话框容器")

                # 2. 在对话框容器的子div中找到 class=operation-bar
                operation_bar = dialog_container.find_element(By.CSS_SELECTOR, ".operation-bar")
                print("✅ 在对话框中找到 operation-bar")

                # 3. 在它的兄弟元素中找到 class=picture-wrapper
                parent = operation_bar.find_element(By.XPATH, "..")
                picture_wrapper = parent.find_element(By.CSS_SELECTOR, ".picture-wrapper")
                print("✅ 找到 picture-wrapper")

                # 4. 在 picture-wrapper 下面找到 class=picture-list
                picture_list = picture_wrapper.find_element(By.CSS_SELECTOR, ".picture-list")
                print("✅ 找到 picture-list")

                # 5. 在 picture-list 下面找 class="picture-item" 的 div
                picture_items = picture_list.find_elements(By.CSS_SELECTOR, ".picture-item")
                visible_items = [item for item in picture_items if item.is_displayed()]
                print(f"✅ 在 picture-list 中找到 {len(visible_items)} 个 picture-item div")

                # 6. 每个 picture-item div 点击一次
                for i, item in enumerate(visible_items):
                    try:
                        # 滚动到元素位置
                        self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", item)
                        time.sleep(0.1)  # 优化：0.2s -> 0.1s

                        # 点击一次 picture-item div
                        self.driver.execute_script("arguments[0].click();", item)
                        selected_count += 1
                        print(f"   ✅ 点击 picture-item {i+1}")
                        time.sleep(0.2)  # 优化：0.3s -> 0.2s

                    except Exception as e:
                        print(f"   ❌ 点击 picture-item {i+1} 失败: {e}")
                        continue

            except Exception as e:
                print(f"❌ 按照对话框DOM结构查找图片失败: {e}")
                print("   回退到通用方法...")

                # 回退到通用方法 - 查找 picture-item div
                image_selectors = [
                    ".picture-item",  # 精确匹配 class="picture-item"
                    "[class='picture-item']",  # 更精确的匹配
                    ".image-item"
                ]

                for selector in image_selectors:
                    try:
                        items = self.driver.find_elements(By.CSS_SELECTOR, selector)
                        visible_items = [item for item in items if item.is_displayed()]
                        print(f"   通过选择器 '{selector}' 找到 {len(visible_items)} 个可见元素")

                        if len(visible_items) > 0:
                            # 每个元素点击一次
                            for i, item in enumerate(visible_items):
                                try:
                                    self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", item)
                                    time.sleep(0.2)
                                    self.driver.execute_script("arguments[0].click();", item)
                                    selected_count += 1
                                    print(f"   ✅ 点击元素 {i+1}")
                                    time.sleep(0.3)
                                except Exception as e:
                                    print(f"   ❌ 点击元素 {i+1} 失败: {e}")
                                    continue

                            if selected_count > 0:
                                break

                    except Exception as e:
                        print(f"   ❌ 使用选择器 '{selector}' 失败: {e}")
                        continue

            print(f"   📊 总共选择了 {selected_count} 张图片")

            if selected_count > 0:
                # 6. 按照DOM结构查找确定按钮
                print("🔍 按照DOM结构查找确定按钮...")
                time.sleep(0.3)  # 优化：0.5s -> 0.3s

                try:
                    if dialog_container and picture_wrapper:
                        # 在对话框容器中查找footer
                        footer = dialog_container.find_element(By.CSS_SELECTOR, ".footer")
                        print("✅ 在对话框中找到 footer")

                        # 在footer下面找确认按钮
                        confirm_buttons = footer.find_elements(By.TAG_NAME, "button")
                        for button in confirm_buttons:
                            if button.is_displayed() and button.is_enabled():
                                button_text = button.text.strip()
                                print(f"   找到footer按钮: '{button_text}'")

                                if button_text in ["确定", "确认", "OK", "ok"]:
                                    try:
                                        button.click()
                                        print(f"✅ 点击footer确定按钮成功: '{button_text}'")
                                        time.sleep(1)
                                        return True
                                    except:
                                        self.driver.execute_script("arguments[0].click();", button)
                                        print(f"✅ 通过JavaScript点击footer确定按钮成功: '{button_text}'")
                                        time.sleep(1)
                                        return True

                        print("❌ 在footer中未找到确定按钮")
                    elif not dialog_container:
                        print("❌ 对话框容器未找到，无法定位footer")
                    else:
                        print("❌ picture_wrapper未找到，无法定位footer")

                except Exception as e:
                    print(f"❌ 按照DOM结构查找确定按钮失败: {e}")

                # 回退到通用方法查找确定按钮
                print("   回退到通用方法查找确定按钮...")
                confirm_button_selectors = [
                    "//button[contains(text(), '确定')]",
                    "//button[contains(text(), '确认')]",
                    ".jx-button--primary"
                ]

                for selector in confirm_button_selectors:
                    try:
                        if selector.startswith("//"):
                            buttons = self.driver.find_elements(By.XPATH, selector)
                        else:
                            buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)

                        for button in buttons:
                            if button.is_displayed() and button.is_enabled():
                                button_text = button.text.strip()
                                if button_text in ["确定", "确认", "OK", "ok"]:
                                    try:
                                        button.click()
                                        print(f"✅ 通用方法点击确定按钮成功: '{button_text}'")
                                        time.sleep(1)
                                        return True
                                    except:
                                        self.driver.execute_script("arguments[0].click();", button)
                                        print(f"✅ 通用方法JavaScript点击确定按钮成功: '{button_text}'")
                                        time.sleep(1)
                                        return True
                    except Exception as e:
                        continue

                print("❌ 所有方法都未找到确定按钮")
                return False
            else:
                print("❌ 没有选择到任何图片")
                return False

        except Exception as e:
            print(f"❌ 选择搜索结果失败: {e}")
            return False

    def save_product(self):
        """保存产品"""
        try:
            print("💾 开始保存产品...")

            # 1. 找到 class=collect-box-editor-footer 的 div
            try:
                footer_editor = self.driver.find_element(By.CSS_SELECTOR, ".collect-box-editor-footer")
                print("✅ 找到 collect-box-editor-footer")

                # 2. 在其下找到"保存"按钮
                save_buttons = footer_editor.find_elements(By.TAG_NAME, "button")
                save_button = None

                for button in save_buttons:
                    if button.is_displayed() and button.is_enabled():
                        button_text = button.text.strip()
                        print(f"   找到按钮: '{button_text}'")

                        if "确定创建" in button_text:
                            save_button = button
                            print(f"✅ 找到确定创建按钮: '{button_text}'")
                            break

                if not save_button:
                    print("❌ 未找到确定创建按钮")
                    return False

                # 3. 点击保存按钮
                try:
                    save_button.click()
                    print("✅ 点击确定创建按钮")
                except:
                    self.driver.execute_script("arguments[0].click();", save_button)
                    print("✅ 通过JavaScript点击确定创建按钮")

                # 等待保存完成
                time.sleep(1)  # 优化：3s -> 1s
                print("✅ 产品创建完成")

            except Exception as e:
                print(f"❌ 查找确定创建按钮失败: {e}")
                return False

            # 4. 关闭创建产品弹窗
            try:
                print("🔍 关闭创建产品弹窗...")

                # 查找关闭按钮
                close_selectors = [
                    ".jx-dialog__headerbtn",  # 通常的关闭按钮
                    "[class*='close']",
                    ".close",
                    "button[aria-label='Close']",
                    ".jx-dialog__close"
                ]

                close_button = None
                for selector in close_selectors:
                    try:
                        close_buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)
                        for button in close_buttons:
                            if button.is_displayed() and button.is_enabled():
                                close_button = button
                                print(f"✅ 找到关闭按钮: {selector}")
                                break
                        if close_button:
                            break
                    except:
                        continue

                if close_button:
                    try:
                        close_button.click()
                        print("✅ 点击关闭按钮")
                    except:
                        self.driver.execute_script("arguments[0].click();", close_button)
                        print("✅ 通过JavaScript点击关闭按钮")

                    time.sleep(1)
                else:
                    print("⚠️ 未找到关闭按钮，尝试按ESC键关闭")
                    from selenium.webdriver.common.keys import Keys
                    self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                    time.sleep(1)

                print("✅ 产品保存并关闭弹窗完成")
                return True

            except Exception as e:
                print(f"❌ 关闭弹窗失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 发布产品失败: {e}")
            return False

    def try_select_all_button(self):
        """尝试使用全选按钮"""
        try:
            print("   🔍 查找全选按钮...")

            # 扩展的全选按钮选择器
            select_all_selectors = [
                "input[type='checkbox'][class*='select-all']",
                "input[type='checkbox'][class*='all']",
                ".select-all",
                "[class*='全选']",
                "[class*='selectAll']",
                ".checkbox-all",
                "label[class*='select-all']"
            ]

            for selector in select_all_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            element.click()
                            print(f"   ✅ 点击全选按钮: {selector}")
                            time.sleep(0.5)
                            return True
                except:
                    continue

            # 尝试XPath查找包含"全选"文本的元素
            try:
                xpath_selectors = [
                    "//input[@type='checkbox' and contains(@class, 'all')]",
                    "//label[contains(text(), '全选')]",
                    "//span[contains(text(), '全选')]",
                    "//*[contains(text(), '全选') and (@type='checkbox' or contains(@class, 'checkbox'))]"
                ]

                for xpath in xpath_selectors:
                    elements = self.driver.find_elements(By.XPATH, xpath)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            element.click()
                            print(f"   ✅ 通过XPath点击全选: {xpath}")
                            time.sleep(0.5)
                            return True
            except:
                pass

            print("   ❌ 未找到全选按钮")
            return False

        except Exception as e:
            print(f"   ❌ 查找全选按钮失败: {e}")
            return False

    def try_select_all_checkboxes(self):
        """尝试选择所有复选框"""
        try:
            print("   🔍 查找并选择所有图片复选框...")

            checkbox_selectors = [
                ".image-item input[type='checkbox']",
                ".img-item input[type='checkbox']",
                "[class*='image'] input[type='checkbox']",
                "[class*='photo'] input[type='checkbox']",
                "[class*='picture'] input[type='checkbox']",
                ".item input[type='checkbox']",
                "input[type='checkbox']"  # 最后尝试所有复选框
            ]

            selected_count = 0

            for selector in checkbox_selectors:
                try:
                    checkboxes = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    print(f"   通过选择器 '{selector}' 找到 {len(checkboxes)} 个复选框")

                    for checkbox in checkboxes:
                        try:
                            if (checkbox.is_displayed() and checkbox.is_enabled() and
                                not checkbox.is_selected()):
                                checkbox.click()
                                selected_count += 1
                                time.sleep(0.1)
                                print(f"     ✅ 选择复选框 {selected_count}")
                        except:
                            continue

                    if selected_count > 0:
                        break  # 如果已经选择了一些，就不用尝试其他选择器了

                except:
                    continue

            print(f"   📊 总共选择了 {selected_count} 个复选框")
            return selected_count > 0

        except Exception as e:
            print(f"   ❌ 选择复选框失败: {e}")
            return False

    def try_select_all_images(self):
        """尝试直接点击图片来选择"""
        try:
            print("   🔍 尝试直接点击图片来选择...")

            # 等待搜索结果加载完成
            time.sleep(1)  # 减少等待时间

            # 根据截图和之前的测试日志，优先使用找到图片的选择器
            image_selectors = [
                "[class*='picture-item']",  # 之前测试中找到了108个元素
                ".picture-item",
                ".image-item",
                ".img-item",
                "[class*='image-card']",
                "[class*='photo-item']",
                "[class*='thumbnail']",
                ".item img",
                "img"
            ]

            selected_count = 0

            for selector in image_selectors:
                try:
                    images = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    visible_images = [img for img in images if img.is_displayed()]
                    print(f"   通过选择器 '{selector}' 找到 {len(visible_images)} 个可见图片元素")

                    if len(visible_images) > 0:
                        # 根据截图，只选择前3张图片（包装图片）
                        for i, image in enumerate(visible_images[:3]):
                            try:
                                # 滚动到图片位置确保可见
                                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", image)
                                time.sleep(0.5)

                                # 尝试点击图片
                                image.click()
                                selected_count += 1
                                print(f"     ✅ 点击图片 {i+1}")
                                time.sleep(0.3)  # 减少等待时间

                            except Exception as e:
                                print(f"     ❌ 点击图片 {i+1} 失败: {e}")
                                # 如果直接点击失败，尝试JavaScript点击
                                try:
                                    self.driver.execute_script("arguments[0].click();", image)
                                    selected_count += 1
                                    print(f"     ✅ 通过JavaScript点击图片 {i+1}")
                                    time.sleep(0.5)
                                except:
                                    continue

                        # 如果成功选择了图片，就不再尝试其他选择器
                        if selected_count > 0:
                            break

                except Exception as e:
                    print(f"   ❌ 使用选择器 '{selector}' 失败: {e}")
                    continue

            print(f"   📊 总共点击了 {selected_count} 张图片")
            return selected_count > 0

        except Exception as e:
            print(f"   ❌ 点击图片失败: {e}")
            return False

    def try_other_selection_methods(self):
        """尝试其他选择方法"""
        try:
            print("   🔍 尝试其他选择方法...")

            # 方法1：查找并点击可能的选择按钮
            selection_button_selectors = [
                "button[class*='select']",
                ".btn-select",
                "[class*='选择']",
                "button:contains('选择')"
            ]

            for selector in selection_button_selectors:
                try:
                    buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            button_text = button.text.strip()
                            if "选择" in button_text or "select" in button_text.lower():
                                button.click()
                                print(f"   ✅ 点击选择按钮: '{button_text}'")
                                time.sleep(0.5)
                                return True
                except:
                    continue

            # 方法2：尝试键盘快捷键 Ctrl+A
            try:
                from selenium.webdriver.common.keys import Keys
                from selenium.webdriver.common.action_chains import ActionChains

                actions = ActionChains(self.driver)
                actions.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
                print("   ✅ 尝试Ctrl+A全选")
                time.sleep(0.5)
                return True
            except:
                pass

            print("   ❌ 其他选择方法都失败了")
            return False

        except Exception as e:
            print(f"   ❌ 其他选择方法失败: {e}")
            return False

    def confirm_image_selection(self):
        """确认图片选择，点击确定按钮"""
        try:
            print("🔍 确认图片选择...")

            # 等待选择完成
            time.sleep(1)

            # 根据截图，查找"确定"按钮
            confirm_button_selectors = [
                "//button[contains(text(), '确定')]",
                "//button[contains(text(), '确认')]",
                "//button[contains(text(), 'OK')]",
                "//button[contains(text(), 'ok')]",
                ".confirm-btn",
                ".btn-confirm",
                "button[class*='confirm']",
                "button[class*='primary']",  # 通常确定按钮是主要按钮
                ".jx-button--primary"  # 根据之前的日志，可能使用jx框架
            ]

            for selector in confirm_button_selectors:
                try:
                    if selector.startswith("//"):
                        # XPath选择器
                        buttons = self.driver.find_elements(By.XPATH, selector)
                    else:
                        # CSS选择器
                        buttons = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    for button in buttons:
                        if button.is_displayed() and button.is_enabled():
                            button_text = button.text.strip()
                            button_class = button.get_attribute("class") or ""

                            print(f"   找到按钮: text='{button_text}', class='{button_class[:30]}...'")

                            # 检查是否是确定按钮
                            if (button_text in ["确定", "确认", "OK", "ok"] or
                                "confirm" in button_class.lower() or
                                "primary" in button_class.lower()):

                                try:
                                    button.click()
                                    print(f"✅ 点击确定按钮: '{button_text}'")
                                    time.sleep(1)  # 等待操作完成
                                    return True
                                except:
                                    # 如果直接点击失败，尝试JavaScript点击
                                    self.driver.execute_script("arguments[0].click();", button)
                                    print(f"✅ 通过JavaScript点击确定按钮: '{button_text}'")
                                    time.sleep(1)
                                    return True

                except Exception as e:
                    print(f"   ❌ 使用选择器 '{selector}' 查找确定按钮失败: {e}")
                    continue

            # 如果没有找到明确的确定按钮，尝试查找弹窗底部的按钮
            try:
                print("   🔍 查找弹窗底部的按钮...")

                # 查找弹窗容器
                dialog_selectors = [
                    ".jx-dialog",
                    ".dialog",
                    ".modal",
                    ".popup",
                    "[class*='dialog']",
                    "[class*='modal']"
                ]

                for dialog_selector in dialog_selectors:
                    try:
                        dialogs = self.driver.find_elements(By.CSS_SELECTOR, dialog_selector)
                        for dialog in dialogs:
                            if dialog.is_displayed():
                                # 在弹窗中查找按钮
                                dialog_buttons = dialog.find_elements(By.TAG_NAME, "button")

                                # 通常确定按钮在最后或者是主要按钮
                                for button in dialog_buttons:
                                    if button.is_displayed() and button.is_enabled():
                                        button_text = button.text.strip()
                                        button_class = button.get_attribute("class") or ""

                                        # 如果是确定相关的按钮
                                        if (button_text in ["确定", "确认", "OK", "ok"] or
                                            "primary" in button_class.lower() or
                                            "confirm" in button_class.lower()):

                                            try:
                                                button.click()
                                                print(f"✅ 点击弹窗中的确定按钮: '{button_text}'")
                                                time.sleep(1)
                                                return True
                                            except:
                                                self.driver.execute_script("arguments[0].click();", button)
                                                print(f"✅ 通过JavaScript点击弹窗中的确定按钮: '{button_text}'")
                                                time.sleep(1)
                                                return True
                    except:
                        continue

            except Exception as e:
                print(f"   ❌ 查找弹窗按钮失败: {e}")

            print("❌ 未找到确定按钮")
            return False

        except Exception as e:
            print(f"❌ 确认图片选择失败: {e}")
            return False



    def select_color_attribute(self, color_value, color_index=0):
        """选择颜色属性"""
        try:
            print(f"🎨 开始选择颜色属性: {color_value} (index={color_index})")

            # 1. 找到颜色信息列表容器
            try:
                color_info_list = self.driver.find_element(By.CSS_SELECTOR, ".color-info-list")
                print("✅ 找到颜色信息列表容器")
            except Exception:
                print("❌ 未找到颜色信息列表容器 (.color-info-list)")
                return False

            color_units = self._get_color_units(color_info_list)
            if color_units:
                target_position = min(color_index, len(color_units) - 1)
                target_container = color_units[target_position]
                print(f"🎯 使用第 {target_position + 1} 个颜色单元")
            else:
                target_container = color_info_list
                print("ℹ️ 未能区分颜色单元，使用颜色容器作为目标")

            # 2. 找到并点击颜色按钮
            try:
                button_selectors = [
                    ".jx-input__suffix",
                    ".jx-cascader",
                    ".color-selector",
                    "button",
                ]

                color_button = None
                for scope in [target_container, color_info_list]:
                    for selector in button_selectors:
                        try:
                            buttons = scope.find_elements(By.CSS_SELECTOR, selector)
                        except Exception:
                            continue

                        for button in buttons:
                            if not button.is_displayed():
                                continue
                            button_text = (button.text or "").strip()
                            button_class = (button.get_attribute("class") or "").lower()
                            if any(keyword in button_text for keyword in ["移除", "删除"]):
                                continue
                            if "remove" in button_class or "delete" in button_class:
                                continue
                            color_button = button
                            break
                        if color_button:
                            break
                    if color_button:
                        break

                if not color_button:
                    print("❌ 未找到颜色按钮")
                    return False

                try:
                    color_button.click()
                except Exception:
                    self.driver.execute_script("arguments[0].click();", color_button)
                print("✅ 成功点击颜色按钮")
                time.sleep(0.5)  # 等待界面响应
            except Exception as e:
                print(f"❌ 颜色按钮点击失败: {e}")
                return False

            # 3. 找到颜色输入框并输入颜色值
            try:
                color_input = None
                selectors = [
                    "input.jx-input__inner",
                    "input",
                    ".jx-input input",
                    "[placeholder*='颜色']",
                    "[placeholder*='color']"
                ]

                for scope in [target_container, color_info_list]:
                    for selector in selectors:
                        try:
                            color_input = scope.find_element(By.CSS_SELECTOR, selector)
                            if color_input.is_displayed() and color_input.is_enabled():
                                print(f"✅ 找到颜色输入框: {selector}")
                                break
                        except Exception:
                            continue
                    if color_input:
                        break

                if not color_input:
                    print("❌ 未找到颜色输入框")
                    return False

                color_input.clear()
                color_input.send_keys(color_value)
                print(f"✅ 输入颜色值: {color_value}")
                time.sleep(1)  # 等待下拉选项出现
            except Exception as e:
                print(f"❌ 颜色输入失败: {e}")
                return False

            # 4. 处理颜色选择下拉框
            return self.handle_color_dropdown(color_value)

        except Exception as e:
            print(f"❌ 选择颜色属性失败: {e}")
            return False

    def handle_color_dropdown(self, color_value):
        """处理颜色选择下拉框"""
        try:
            print("🔍 查找颜色选择下拉框...")

            # 等待下拉框出现
            time.sleep(1)

            # 尝试多种下拉框选择器
            dropdown_selectors = [
                ".jx-cascader__suggestion-panel",
                ".jx-cascader__dropdown",
                ".jx-popper.jx-cascader__dropdown",
                ".jx-popper.is-pure.is-light.jx-cascader__dropdown",
                ".pddkj-color-cascader__popper",
                "[class*='cascader__dropdown']",
                "[class*='color-cascader']"
            ]

            dropdown = None
            for selector in dropdown_selectors:
                try:
                    dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if dropdowns:
                        for dd in dropdowns:
                            if dd.is_displayed():
                                dropdown = dd
                                print(f"✅ 找到颜色下拉框: {selector}")
                                break
                    if dropdown:
                        break
                except:
                    continue

            if not dropdown:
                print("❌ 未找到颜色下拉框")
                return False

            # 查找所有候选项
            try:
                suggestion_items = dropdown.find_elements(By.CSS_SELECTOR, ".jx-cascader__suggestion-item")
                print(f"🔍 找到 {len(suggestion_items)} 个候选项")
            except Exception:
                suggestion_items = []

            if not suggestion_items:
                try:
                    suggestion_items = dropdown.find_elements(By.CSS_SELECTOR, "li")
                    print(f"🔍 退化查找 li，数量 {len(suggestion_items)}")
                except Exception:
                    suggestion_items = []

            target_element = None

            # 优先精确匹配
            for item in suggestion_items:
                try:
                    text = (item.text or "").strip()
                    if text == color_value:
                        target_element = item
                        print(f"🎯 精确匹配颜色: {text}")
                        break
                except Exception:
                    continue

            if not target_element:
                # 尝试匹配“创建自定义颜色-xxx”
                for item in suggestion_items:
                    try:
                        text = (item.text or "").strip()
                        if "创建自定义颜色" in text and color_value in text:
                            target_element = item
                            print(f"🎯 匹配自定义颜色项: {text}")
                            break
                    except Exception:
                        continue

            if not target_element and suggestion_items:
                target_element = suggestion_items[0]
                print(f"ℹ️ 未找到精确匹配，选择第一个候选项: {(target_element.text or '').strip()}")

            if not target_element:
                print("❌ 未找到可点击的颜色选项")
                return False

            try:
                target_element.click()
            except Exception:
                self.driver.execute_script("arguments[0].click();", target_element)
            print(f"✅ 选择颜色项: {(target_element.text or '').strip()}")
            time.sleep(0.5)
            return True

        except Exception as e:
            print(f"❌ 处理颜色下拉框失败: {e}")
            return False

    def select_size_attribute(self, size_value):
        """选择尺码属性"""
        try:
            print(f"📏 开始选择尺码属性: {size_value}")

            # 解析尺码范围，例如 "39-46" -> ["39", "40", "41", "42", "43", "44", "45", "46"]
            size_list = self.parse_size_range(size_value)
            print(f"📏 解析的尺码列表: {size_list}")
            # 记录实际选择的尺码，供SKU表格填写使用
            self.actual_selected_sizes = size_list

            # 1. 找到SKU属性值列表容器
            try:
                sku_property_list = self.driver.find_element(By.CSS_SELECTOR, ".sku-property-value-list")
                print("✅ 找到SKU属性值列表容器")
            except:
                print("❌ 未找到SKU属性值列表容器 (.sku-property-value-list)")
                return False

            # 2. 找到复选框组
            try:
                checkbox_group = sku_property_list.find_element(By.CSS_SELECTOR, ".jx-checkbox-group")
                print("✅ 找到复选框组")
            except:
                print("❌ 未找到复选框组 (.jx-checkbox-group)")
                return False

            # 3. 找到所有label元素
            labels = checkbox_group.find_elements(By.CSS_SELECTOR, "label")
            print(f"🔍 找到 {len(labels)} 个label元素")

            if not labels:
                print("❌ 未找到任何label元素")
                return False

            # 4. 遍历并选择匹配的尺码
            selected_count = 0

            # 只调试前10个label，避免输出过多
            debug_count = min(10, len(labels))
            print(f"🔍 调试前{debug_count}个label的结构:")

            for i in range(debug_count):
                label = labels[i]
                try:
                    # 获取label的完整HTML结构
                    label_html = label.get_attribute('outerHTML')[:200] + "..." if len(label.get_attribute('outerHTML')) > 200 else label.get_attribute('outerHTML')
                    print(f"   label{i+1} HTML: {label_html}")

                    # 获取label的文本内容
                    label_text = label.text.strip()
                    print(f"   label{i+1} 文本: '{label_text}'")

                    # 查找所有span
                    spans = label.find_elements(By.CSS_SELECTOR, "span")
                    print(f"   label{i+1} span数量: {len(spans)}")

                    for j, span in enumerate(spans):
                        span_text = span.text.strip()
                        span_class = span.get_attribute('class') or ''
                        print(f"      span{j+1}: '{span_text}' (class: {span_class})")

                        # 查找span下的div
                        divs = span.find_elements(By.CSS_SELECTOR, "div")
                        if divs:
                            for k, div in enumerate(divs):
                                div_text = div.text.strip()
                                div_class = div.get_attribute('class') or ''
                                print(f"         div{k+1}: '{div_text}' (class: {div_class})")

                except Exception as e:
                    print(f"   ❌ 调试label{i+1}失败: {e}")

            # 现在尝试实际的尺码选择
            print(f"\n📏 开始实际的尺码选择...")

            for i, label in enumerate(labels):
                try:
                    # 获取label的所有文本内容
                    label_text = label.text.strip()

                    # 检查label文本是否包含我们需要的尺码，但排除带"-"的标签
                    found_size = None

                    # 首先检查是否包含"-"，如果包含则跳过
                    if '-' in label_text:
                        print(f"   ⚠️ label{i+1}包含'-'，跳过: '{label_text}'")
                        continue

                    for size in size_list:
                        # 更精确的匹配：确保尺码是独立的数字，不是其他数字的一部分
                        if (f" {size} " in f" {label_text} " or
                            label_text.startswith(f"{size} ") or
                            label_text.endswith(f" {size}") or
                            label_text == size):
                            found_size = size
                            break

                    if found_size:
                        print(f"   🎯 label{i+1}包含需要的尺码: {found_size} (文本: '{label_text}')")

                        # 尝试点击label本身
                        try:
                            label.click()
                            selected_count += 1
                            print(f"   ✅ 成功选择尺码: {found_size}")
                        except:
                            # 如果点击失败，尝试JavaScript点击
                            self.driver.execute_script("arguments[0].click();", label)
                            selected_count += 1
                            print(f"   ✅ 成功选择尺码（JavaScript）: {found_size}")

                        time.sleep(0.3)  # 短暂等待

                except Exception as e:
                    print(f"   ❌ 处理label{i+1}失败: {e}")

                # 只处理前50个label，避免过多处理
                if i >= 50:
                    break

            print(f"📏 尺码选择完成，共选择了 {selected_count} 个尺码")

            if selected_count > 0:
                print("✅ 尺码属性选择成功")

                # 选择完尺码后，处理尺码表选择
                print("📐 开始处理尺码表选择...")
                if not self.select_size_chart(size_list):
                    print("⚠️ 尺码表选择失败，但继续执行")

                return True
            else:
                print("⚠️ 未选择任何尺码")
                return False

        except Exception as e:
            print(f"❌ 选择尺码属性失败: {e}")
            return False

    def parse_size_range(self, size_value):
        """解析尺码范围，例如 "35-42" -> ["35", "36", "37", "38", "39", "40", "41", "42"]"""
        try:
            if '-' in size_value:
                # 处理范围格式，如 "35-42"
                start, end = size_value.split('-')
                start_num = int(start.strip())
                end_num = int(end.strip())
                return [str(i) for i in range(start_num, end_num + 1)]
            elif ',' in size_value:
                # 处理逗号分隔格式，如 "35,36,37,38"
                return [size.strip() for size in size_value.split(',')]
            else:
                # 单个尺码
                return [size_value.strip()]
        except Exception as e:
            print(f"❌ 解析尺码范围失败: {e}")
            return [size_value]  # 返回原始值作为备用

    def select_size_chart(self, size_list):
        """选择尺码表 - 根据用户需求完善的版本"""
        try:
            print("📐 开始选择尺码表...")
            print(f"📏 当前尺码列表: {size_list}")

            # 1. 找到class=size-chart-box的div
            try:
                size_chart_box = self.driver.find_element(By.CSS_SELECTOR, ".size-chart-box")
                print("✅ 找到尺码表容器 (.size-chart-box)")
            except:
                print("❌ 未找到尺码表容器 (.size-chart-box)")
                return False

            # 2. 在size-chart-box下找到div下的label，内容包含"尺码表"
            try:
                # 先尝试精确匹配
                size_chart_label = None
                try:
                    size_chart_label = size_chart_box.find_element(By.XPATH, ".//div//label[contains(text(), '尺码表')]")
                except:
                    # 如果精确匹配失败，尝试更宽泛的匹配
                    all_labels = size_chart_box.find_elements(By.TAG_NAME, "label")
                    for label in all_labels:
                        if "尺码表" in label.text:
                            size_chart_label = label
                            break

                if size_chart_label:
                    print("✅ 找到尺码表标签")
                    print(f"   标签文本: '{size_chart_label.text}'")
                else:
                    raise Exception("未找到尺码表标签")

            except:
                print("❌ 未找到包含'尺码表'的label")
                # 调试：显示所有label
                try:
                    all_labels = size_chart_box.find_elements(By.TAG_NAME, "label")
                    print(f"🔍 调试：size-chart-box中找到 {len(all_labels)} 个label:")
                    for i, label in enumerate(all_labels):
                        print(f"   label{i+1}: '{label.text}'")
                except:
                    pass
                return False

            # 3. 找到label同级的div下的input（递归查找）
            try:
                print("🔍 查找label同级的div下的input...")

                # 获取label的父元素
                label_parent = size_chart_label.find_element(By.XPATH, "..")
                print(f"   label父元素标签: {label_parent.tag_name}")
                print(f"   label父元素class: {label_parent.get_attribute('class')}")

                # 在父元素的同级div中递归查找input
                input_element = None
                sibling_divs = label_parent.find_elements(By.XPATH, "../div")
                print(f"   找到 {len(sibling_divs)} 个同级div")

                for i, div in enumerate(sibling_divs):
                    # 递归查找input
                    inputs = div.find_elements(By.XPATH, ".//input")
                    print(f"   div{i+1}中找到 {len(inputs)} 个input")

                    # 调试：显示div的class和input的详细信息
                    div_class = div.get_attribute('class') or ''
                    print(f"      div{i+1} class: {div_class}")

                    for j, inp in enumerate(inputs):
                        inp_type = inp.get_attribute('type') or ''
                        inp_class = inp.get_attribute('class') or ''
                        inp_placeholder = inp.get_attribute('placeholder') or ''
                        inp_value = inp.get_attribute('value') or ''
                        print(f"         input{j+1}: type='{inp_type}', class='{inp_class[:50]}...', placeholder='{inp_placeholder}', value='{inp_value}'")

                    if inputs:
                        input_element = inputs[0]  # 取第一个input
                        print(f"   ✅ 在div{i+1}中找到input元素")
                        break

                if not input_element:
                    print("❌ 未找到尺码表相关的input元素")
                    return False

                print("✅ 找到尺码表input元素")

                # 额外验证：检查input是否与尺码表相关
                input_class = input_element.get_attribute('class') or ''
                input_placeholder = input_element.get_attribute('placeholder') or ''
                input_type = input_element.get_attribute('type') or ''
                print(f"   🔍 选中的input详情: type='{input_type}', class='{input_class}', placeholder='{input_placeholder}'")

            except Exception as e:
                print(f"❌ 查找尺码表input失败: {e}")
                return False

            # 4. 点击input元素触发下拉框展开
            try:
                print("🖱️ 点击尺码表input元素触发下拉框...")

                # 滚动到元素位置
                self.driver.execute_script("arguments[0].scrollIntoView(true);", input_element)
                time.sleep(0.5)

                # 尝试多种点击方式确保下拉框展开
                try:
                    # 方法1：普通点击
                    input_element.click()
                    print("✅ 普通点击成功")
                except:
                    try:
                        # 方法2：JavaScript点击
                        self.driver.execute_script("arguments[0].click();", input_element)
                        print("✅ JavaScript点击成功")
                    except:
                        # 方法3：发送空格键或回车键
                        from selenium.webdriver.common.keys import Keys
                        input_element.send_keys(Keys.SPACE)
                        print("✅ 发送空格键成功")

                # 等待下拉框出现
                time.sleep(2)

                # 验证下拉框是否出现
                dropdown_appeared = False
                for attempt in range(3):
                    try:
                        poppers = self.driver.find_elements(By.CSS_SELECTOR, ".jx-popper")
                        visible_poppers = [p for p in poppers if p.is_displayed()]
                        if visible_poppers:
                            dropdown_appeared = True
                            print(f"✅ 下拉框已出现，找到 {len(visible_poppers)} 个可见下拉框")
                            break
                        else:
                            print(f"⚠️ 尝试 {attempt + 1}/3: 下拉框未出现，重新点击...")
                            input_element.click()
                            time.sleep(1)
                    except:
                        time.sleep(1)

                if not dropdown_appeared:
                    print("❌ 多次尝试后下拉框仍未出现")
                    return False

            except Exception as e:
                print(f"❌ 点击尺码表input失败: {e}")
                return False

            # 5. 查找出现的下拉框 class=jx-popper is-pure is-light jx-select__popper
            try:
                print("🔍 查找尺码表下拉框...")

                # 等待下拉框出现
                time.sleep(3)  # 等待下拉框完全加载

                # 查找所有可能的下拉框
                all_poppers = self.driver.find_elements(By.CSS_SELECTOR, ".jx-popper")
                print(f"🔍 调试：页面上找到 {len(all_poppers)} 个jx-popper元素")

                popper_div = None

                # 优先查找精确匹配的下拉框
                try:
                    exact_popper = self.driver.find_element(By.CSS_SELECTOR, ".jx-popper.is-pure.is-light.jx-select__popper")
                    if exact_popper.is_displayed():
                        popper_div = exact_popper
                        print("✅ 找到精确匹配的尺码表下拉框")
                except:
                    print("⚠️ 未找到精确匹配的下拉框")

                # 如果没找到精确匹配，查找所有可见的popper
                if not popper_div:
                    for i, popper in enumerate(all_poppers):
                        if popper.is_displayed():
                            class_name = popper.get_attribute('class')
                            print(f"   popper{i+1}: {class_name}")

                            # 检查是否包含尺码表相关的内容
                            try:
                                # 查找是否包含尺码表相关的li元素
                                li_elements = popper.find_elements(By.TAG_NAME, "li")
                                if li_elements:
                                    # 检查li元素的内容
                                    sample_texts = []
                                    for j, li in enumerate(li_elements[:3]):  # 只检查前3个
                                        li_text = li.text.strip()
                                        if li_text:
                                            sample_texts.append(li_text)

                                    print(f"      popper{i+1}的li内容示例: {sample_texts}")

                                    # 如果包含尺码表相关的关键词，选择这个popper
                                    combined_text = ' '.join(sample_texts)
                                    if any(keyword in combined_text for keyword in ['男鞋', '女鞋', '尺码', '码表', 'size']):
                                        popper_div = popper
                                        print(f"✅ 找到包含尺码表关键词的下拉框: popper{i+1}")
                                        break
                                    elif '店铺' in combined_text:
                                        print(f"   popper{i+1}是店铺相关下拉框，跳过")
                                        continue
                            except:
                                pass

                # 如果还是没找到，使用最后一个可见的popper（通常是最新出现的）
                if not popper_div:
                    for popper in reversed(all_poppers):
                        if popper.is_displayed():
                            popper_div = popper
                            print("⚠️ 使用最后一个可见的下拉框")
                            break

                if not popper_div:
                    print("❌ 未找到任何可见的下拉框")
                    return False

            except Exception as e:
                print(f"❌ 查找尺码表下拉框失败: {e}")
                return False

            # 6. 在下拉框中找到li标签 - 根据实际DOM结构调整
            try:
                print("🔍 查找下拉框中的li元素...")

                # 调试：显示popper的完整结构
                try:
                    all_divs = popper_div.find_elements(By.TAG_NAME, "div")
                    print(f"🔍 调试：popper下总共有 {len(all_divs)} 个div")
                    for i, div in enumerate(all_divs[:8]):  # 显示前8个
                        class_name = div.get_attribute('class') or ''
                        print(f"   div{i+1}: class='{class_name}'")
                except:
                    pass

                # 根据实际结构查找li元素
                # 尝试多种路径查找li元素
                li_elements = []

                # 方法1：直接在popper下查找所有li
                li_elements = popper_div.find_elements(By.TAG_NAME, "li")
                print(f"   方法1：直接查找，找到 {len(li_elements)} 个li元素")

                # 方法2：在jx-collapse下查找li
                if not li_elements:
                    try:
                        collapse_div = popper_div.find_element(By.CSS_SELECTOR, ".jx-collapse")
                        li_elements = collapse_div.find_elements(By.TAG_NAME, "li")
                        print(f"   方法2：在jx-collapse下查找，找到 {len(li_elements)} 个li元素")
                    except:
                        print("   方法2：未找到jx-collapse元素")

                # 方法3：在scrollbar下查找li
                if not li_elements:
                    try:
                        scrollbar_div = popper_div.find_element(By.CSS_SELECTOR, ".jx-scrollbar")
                        li_elements = scrollbar_div.find_elements(By.TAG_NAME, "li")
                        print(f"   方法3：在jx-scrollbar下查找，找到 {len(li_elements)} 个li元素")
                    except:
                        print("   方法3：未找到jx-scrollbar元素")

                # 方法4：查找所有可能的选项元素（不限于li）
                if not li_elements:
                    try:
                        # 查找可能的选项元素
                        option_selectors = [
                            ".jx-collapse-item",
                            ".jx-select-dropdown__item",
                            "[role='option']",
                            ".option-item",
                            "div[data-value]"
                        ]

                        for selector in option_selectors:
                            options = popper_div.find_elements(By.CSS_SELECTOR, selector)
                            if options:
                                print(f"   方法4：使用选择器 '{selector}' 找到 {len(options)} 个选项")
                                # 将这些选项当作li_elements处理
                                li_elements = options
                                break
                    except:
                        pass

                if not li_elements:
                    print("❌ 未找到任何li元素或选项元素")
                    return False

                print(f"✅ 找到 {len(li_elements)} 个选项")

                # 调试：显示所有选项的文本
                print("🔍 调试：所有选项内容:")
                for i, li in enumerate(li_elements):
                    try:
                        li_text = li.text.strip()
                        li_tag = li.tag_name
                        li_class = li.get_attribute('class') or ''

                        # 如果直接获取的文本为空，尝试获取innerHTML或其他属性
                        if not li_text:
                            try:
                                # 尝试获取innerHTML
                                inner_html = li.get_attribute('innerHTML')
                                if inner_html:
                                    # 简单提取文本（去除HTML标签）
                                    import re
                                    li_text = re.sub(r'<[^>]+>', '', inner_html).strip()

                                # 如果还是空，尝试获取子元素的文本
                                if not li_text:
                                    child_elements = li.find_elements(By.XPATH, ".//*")
                                    for child in child_elements:
                                        child_text = child.text.strip()
                                        if child_text:
                                            li_text = child_text
                                            break

                                # 如果还是空，尝试获取data属性
                                if not li_text:
                                    data_value = li.get_attribute('data-value') or li.get_attribute('value')
                                    if data_value:
                                        li_text = f"[data-value: {data_value}]"

                            except:
                                pass

                        print(f"   {li_tag}{i+1}: '{li_text}' (class: {li_class[:50]}...)")

                        # 额外调试：显示li的HTML结构
                        if i < 2:  # 只显示前2个的详细结构
                            try:
                                outer_html = li.get_attribute('outerHTML')[:200] + "..." if len(li.get_attribute('outerHTML')) > 200 else li.get_attribute('outerHTML')
                                print(f"      HTML: {outer_html}")
                            except:
                                pass

                    except:
                        print(f"   选项{i+1}: 无法获取文本")

            except Exception as e:
                print(f"❌ 查找li元素失败: {e}")
                return False

            # 7. 根据已判断的鞋子类型和具体类别选择合适的li
            try:
                print("🎯 根据已判断的鞋子类型选择合适的尺码表...")
                print(f"   当前鞋子类型: {self.current_shoe_type}")
                if self.shoe_category_type:
                    print(f"   具体类别类型: {self.shoe_category_type}")

                # 使用已经判断好的鞋子类型
                is_mens_shoe = (self.current_shoe_type == "男鞋")

                target_li = None

                def get_li_text(li_element):
                    """获取li元素的文本内容，尝试多种方法"""
                    try:
                        # 方法1：直接获取text
                        text = li_element.text.strip()
                        if text:
                            return text

                        # 方法2：获取innerHTML并提取文本
                        inner_html = li_element.get_attribute('innerHTML')
                        if inner_html:
                            import re
                            text = re.sub(r'<[^>]+>', '', inner_html).strip()
                            if text:
                                return text

                        # 方法3：获取textContent属性
                        text_content = li_element.get_attribute('textContent')
                        if text_content:
                            text = text_content.strip()
                            if text:
                                return text

                        # 方法4：获取innerText属性
                        inner_text = li_element.get_attribute('innerText')
                        if inner_text:
                            text = inner_text.strip()
                            if text:
                                return text

                        # 方法5：获取子元素的文本
                        child_elements = li_element.find_elements(By.XPATH, ".//*")
                        for child in child_elements:
                            child_text = child.text.strip()
                            if child_text:
                                return child_text

                        # 方法6：获取data属性
                        data_value = li_element.get_attribute('data-value') or li_element.get_attribute('value')
                        if data_value:
                            return f"[{data_value}]"

                        # 方法7：获取title属性
                        title = li_element.get_attribute('title')
                        if title:
                            return title.strip()

                        return ""
                    except Exception as e:
                        print(f"⚠️ 获取li文本失败: {e}")
                        return ""

                # 显示所有可用选项
                print(f"📊 总共找到 {len(li_elements)} 个li选项")
                for i, li in enumerate(li_elements):
                    li_text = get_li_text(li)
                    print(f"   选项{i+1}: 文本='{li_text}'")

                # 优先根据具体类别类型查找精确匹配
                if self.shoe_category_type:
                    print(f"🎯 优先查找'{self.shoe_category_type}'相关的尺码表...")
                    for i, li in enumerate(li_elements):
                        li_text = get_li_text(li)
                        # 精确匹配具体类别
                        if self.shoe_category_type in li_text:
                            target_li = li
                            print(f"✅ 找到精确匹配的尺码表选项: {li_text}")
                            break

                # 如果没有找到精确匹配，使用男鞋/女鞋的通用匹配
                if target_li is None and is_mens_shoe:
                    # 判断为男鞋，选择包含"男鞋"或"男士"的选项
                    print("🔍 未找到精确匹配，查找男鞋通用选项...")
                    
                    # 优先查找包含"运动休闲鞋"的选项（作为男鞋的默认选项）
                    for i, li in enumerate(li_elements):
                        li_text = get_li_text(li)
                        if "男士运动休闲鞋" in li_text or "男士休闲运动鞋" in li_text:
                            target_li = li
                            print(f"✅ 找到男鞋默认选项（运动休闲鞋）: {li_text}")
                            break
                    
                    # 如果没找到运动休闲鞋，查找任何包含"男鞋"或"男士"的选项
                    if target_li is None:
                        for i, li in enumerate(li_elements):
                            li_text = get_li_text(li)
                            if "男鞋" in li_text or "男士" in li_text:
                                target_li = li
                                print(f"✅ 找到男鞋备选选项: {li_text}")
                                break
                elif target_li is None and not is_mens_shoe:
                    # 判断为女鞋，查找包含"女鞋"的选项
                    print("🔍 未找到精确匹配，查找女鞋通用选项...")
                    
                    for i, li in enumerate(li_elements):
                        li_text = get_li_text(li)
                        if "女鞋" in li_text or "女士" in li_text:
                            target_li = li
                            print(f"✅ 找到女鞋选项: {li_text}")
                            break

                # 如果没找到特定的选项，使用第一个li作为备选
                if not target_li and li_elements:
                    target_li = li_elements[0]
                    target_li_text = get_li_text(target_li)
                    print(f"⚠️ 未找到特定选项，使用第一个选项: {target_li_text}")

                if target_li:
                    # 为了避免stale element reference错误，重新查找要点击的元素
                    target_li_text = get_li_text(target_li)
                    print(f"🖱️ 准备点击选中的li: {target_li_text}")

                    try:
                        # 方法1：直接点击
                        self.driver.execute_script("arguments[0].click();", target_li)
                        print(f"✅ 成功选择尺码表: {target_li_text}")
                        time.sleep(2)
                        return True
                    except Exception as e:
                        print(f"⚠️ 直接点击失败: {e}")

                        # 方法2：重新查找并点击
                        try:
                            print("🔄 重新查找li元素并点击...")
                            # 重新获取下拉框
                            fresh_popper = self.driver.find_element(By.CSS_SELECTOR, ".jx-popper.is-pure.is-light.jx-select__popper")
                            fresh_li_elements = fresh_popper.find_elements(By.TAG_NAME, "li")

                            # 重新查找目标选项
                            fresh_target_li = None
                            for li in fresh_li_elements:
                                li_text = get_li_text(li)
                                if (is_mens_shoe and "男鞋" in li_text) or (not is_mens_shoe and "女鞋" in li_text):
                                    fresh_target_li = li
                                    break

                            if not fresh_target_li and fresh_li_elements:
                                fresh_target_li = fresh_li_elements[0]

                            if fresh_target_li:
                                self.driver.execute_script("arguments[0].click();", fresh_target_li)
                                print(f"✅ 重新查找后成功选择尺码表")
                                time.sleep(2)
                                return True
                            else:
                                print("❌ 重新查找后仍未找到目标选项")
                                return False

                        except Exception as e2:
                            print(f"❌ 重新查找也失败: {e2}")
                            return False
                else:
                    print("❌ 未找到合适的尺码表选项")
                    return False

            except Exception as e:
                print(f"❌ 选择尺码表选项失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 选择尺码表失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def fill_sku_preview_images(self):
        """填充SKU预览图 - 全选并一件填充"""
        try:
            print("🖼️ 开始填充SKU预览图...")

            # 等待页面完全加载
            time.sleep(3)

            # 滚动到页面底部，确保SKU表格可见
            print("📜 滚动到页面底部，确保SKU表格可见...")
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(2)

            # 1. 按照用户描述的路径找到表格头部容器
            try:
                print("🔍 按照指定路径查找表格头部容器...")

                # 第一步：找到 class=sku-property-list 的 div
                sku_property_list = self.driver.find_element(By.CSS_SELECTOR, ".sku-property-list")
                print("✅ 找到 sku-property-list 容器")

                # 第二步：找到它的同级最后一个 div
                parent = sku_property_list.find_element(By.XPATH, "..")
                sibling_divs = parent.find_elements(By.XPATH, "./div")
                print(f"   找到 {len(sibling_divs)} 个同级div")

                if len(sibling_divs) == 0:
                    print("❌ 未找到同级div")
                    return False

                last_sibling_div = sibling_divs[-1]  # 最后一个div
                print(f"   选择最后一个同级div (第{len(sibling_divs)}个)")

                # 第三步：最后一个div下的第二个div
                last_div_children = last_sibling_div.find_elements(By.XPATH, "./div")
                print(f"   最后一个div下找到 {len(last_div_children)} 个子div")

                if len(last_div_children) < 2:
                    print("❌ 最后一个div下的子div数量不足")
                    return False

                second_div = last_div_children[1]  # 第二个div
                print("   选择第二个子div")

                # 第四步：第二个div下的第三个div
                second_div_children = second_div.find_elements(By.XPATH, "./div")
                print(f"   第二个div下找到 {len(second_div_children)} 个子div")

                if len(second_div_children) < 3:
                    print("❌ 第二个div下的子div数量不足")
                    return False

                third_div = second_div_children[2]  # 第三个div
                print("   选择第三个子div")

                # 第五步：第三个div下的第一个div
                third_div_children = third_div.find_elements(By.XPATH, "./div")
                print(f"   第三个div下找到 {len(third_div_children)} 个子div")

                if len(third_div_children) < 1:
                    print("❌ 第三个div下没有子div")
                    return False

                first_div_level4 = third_div_children[0]  # 第一个div
                print("   选择第一个子div (level4)")

                # 第六步：第一个div下的第一个div
                level4_children = first_div_level4.find_elements(By.XPATH, "./div")
                print(f"   level4 div下找到 {len(level4_children)} 个子div")

                if len(level4_children) < 1:
                    print("❌ level4 div下没有子div")
                    return False

                first_div_level5 = level4_children[0]  # 第一个div
                print("   选择第一个子div (level5)")

                # 第七步：第一个div下的第一个div (这应该是 pro-virtual-table__header)
                level5_children = first_div_level5.find_elements(By.XPATH, "./div")
                print(f"   level5 div下找到 {len(level5_children)} 个子div")

                if len(level5_children) < 1:
                    print("❌ level5 div下没有子div")
                    return False

                table_header = level5_children[0]  # 第一个div，应该是 pro-virtual-table__header
                table_header_class = table_header.get_attribute('class') or ''
                print(f"   找到目标div: class='{table_header_class}'")

                # 验证是否是正确的表格头部
                if 'pro-virtual-table__header' in table_header_class:
                    print("✅ 成功找到 pro-virtual-table__header 容器")
                else:
                    print(f"⚠️ 找到的div class不匹配，但继续尝试: {table_header_class}")

            except Exception as e:
                print(f"❌ 按照指定路径查找表格头部容器失败: {e}")
                return False

            # 2. 点击第一个 div 里面的 label（全选）
            try:
                print("🔍 查找第一个div中的label（全选按钮）...")
                first_div = table_header.find_element(By.XPATH, "./div[1]")
                select_all_label = first_div.find_element(By.TAG_NAME, "label")

                label_class = select_all_label.get_attribute('class') or ''
                print(f"   找到全选label: {label_class}")

                # 点击全选
                self.driver.execute_script("arguments[0].click();", select_all_label)
                print("✅ 成功点击全选按钮")
                time.sleep(2)  # 增加等待时间，确保选择生效

                # 验证是否成功选择了SKU行
                try:
                    # 查找SKU表格体，确认有选中的行
                    sku_table_body = self.driver.find_element(By.CSS_SELECTOR, ".pro-virtual-table__body")
                    selected_rows = sku_table_body.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row.is-selected")
                    print(f"   ✅ 已选中 {len(selected_rows)} 个SKU行")

                    if len(selected_rows) == 0:
                        print("   ⚠️ 没有选中任何SKU行，尝试手动选择...")
                        # 如果全选没有生效，尝试手动选择第一行
                        all_rows = sku_table_body.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row")
                        if all_rows:
                            first_row_checkbox = all_rows[0].find_element(By.CSS_SELECTOR, "label.jx-checkbox")
                            self.driver.execute_script("arguments[0].click();", first_row_checkbox)
                            print("   ✅ 手动选择了第一个SKU行")
                            time.sleep(1)
                except Exception as verify_e:
                    print(f"   ⚠️ 无法验证SKU行选择状态: {verify_e}")

            except Exception as e:
                print(f"❌ 点击全选按钮失败: {e}")
                return False

            # 3. 查找操作按钮 - 可能在同一个 table_header 容器中，或者在兄弟容器中
            try:
                print("🔍 查找操作按钮容器...")

                # 方法1：直接在 table_header 中查找（可能 headerd 就是 header）
                headerd_container = table_header
                print("   方法1：使用当前的 table_header 作为操作容器")

                # 方法2：查找 table_header 的兄弟元素中是否有 headerd
                if not headerd_container or len(headerd_container.find_elements(By.XPATH, "./div")) < 2:
                    print("   方法1失败，尝试查找兄弟元素...")
                    try:
                        # 获取 table_header 的父元素
                        table_parent = table_header.find_element(By.XPATH, "..")
                        # 查找所有兄弟div
                        sibling_divs = table_parent.find_elements(By.XPATH, "./div")
                        print(f"   找到 {len(sibling_divs)} 个兄弟div")

                        for i, sibling in enumerate(sibling_divs):
                            sibling_class = sibling.get_attribute('class') or ''
                            print(f"      兄弟div{i+1}: class='{sibling_class}'")
                            if 'headerd' in sibling_class or 'header' in sibling_class:
                                # 检查这个div是否有足够的子div
                                child_divs = sibling.find_elements(By.XPATH, "./div")
                                if len(child_divs) >= 2:
                                    headerd_container = sibling
                                    print(f"   ✅ 找到合适的操作容器: {sibling_class}")
                                    break
                    except Exception as e:
                        print(f"   查找兄弟元素失败: {e}")

                # 方法3：在更大范围内查找 headerd
                if not headerd_container:
                    print("   方法2失败，尝试在更大范围查找...")
                    try:
                        sku_area = self.driver.find_element(By.CSS_SELECTOR, ".sku-property-list")
                        parent_area = sku_area.find_element(By.XPATH, "../..")
                        headerd_elements = parent_area.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__headerd")
                        if headerd_elements:
                            headerd_container = headerd_elements[0]
                            print("   ✅ 在父级区域找到 pro-virtual-table__headerd 容器")
                        else:
                            # 查找任何包含 header 的虚拟表格元素
                            header_elements = parent_area.find_elements(By.CSS_SELECTOR, "[class*='virtual-table'][class*='header']")
                            for elem in header_elements:
                                child_divs = elem.find_elements(By.XPATH, "./div")
                                if len(child_divs) >= 2:
                                    headerd_container = elem
                                    elem_class = elem.get_attribute('class')
                                    print(f"   ✅ 找到备选操作容器: {elem_class}")
                                    break
                    except Exception as e:
                        print(f"   方法3失败: {e}")

                if not headerd_container:
                    print("❌ 未找到合适的操作容器")
                    return False

                print(f"✅ 最终选择的操作容器: {headerd_container.get_attribute('class')}")

            except Exception as e:
                print(f"❌ 查找操作容器失败: {e}")
                return False

            # 4. 点击 pro-virtual-table__headerd div 下的第二个 div 下的 div 下的 button 按钮
            try:
                print("🔍 查找 headerd 容器下第二个div的button按钮...")

                # 调试：显示headerd_container的所有子div
                headerd_divs = headerd_container.find_elements(By.XPATH, "./div")
                print(f"   headerd容器下找到 {len(headerd_divs)} 个直接子div:")
                for i, div in enumerate(headerd_divs):
                    div_class = div.get_attribute('class') or ''
                    div_text = div.text.strip()[:50] + "..." if len(div.text.strip()) > 50 else div.text.strip()
                    print(f"      div{i+1}: class='{div_class}', text='{div_text}'")

                if len(headerd_divs) < 2:
                    print("❌ headerd容器下的div数量不足")
                    return False

                second_div = headerd_divs[1]  # 第二个div
                second_div_class = second_div.get_attribute('class') or ''
                print(f"   第二个div: class='{second_div_class}'")

                # 查找第二个div下的div
                second_div_children = second_div.find_elements(By.XPATH, "./div")
                print(f"   第二个div下找到 {len(second_div_children)} 个子div")

                if len(second_div_children) < 1:
                    print("❌ 第二个div下没有子div")
                    return False

                # 在第二个div的子div中查找button
                action_button = None
                for i, child_div in enumerate(second_div_children):
                    child_div_class = child_div.get_attribute('class') or ''
                    print(f"      子div{i+1}: class='{child_div_class}'")

                    # 查找这个子div下的button
                    buttons_in_child = child_div.find_elements(By.TAG_NAME, "button")
                    if buttons_in_child:
                        action_button = buttons_in_child[0]
                        button_text = action_button.text.strip()
                        button_class = action_button.get_attribute('class') or ''
                        print(f"         找到button: '{button_text}' (class: {button_class})")
                        break

                # 如果在子div中没找到，直接在第二个div下查找
                if not action_button:
                    print("   在子div中未找到button，直接在第二个div下查找...")
                    direct_buttons = second_div.find_elements(By.TAG_NAME, "button")
                    if direct_buttons:
                        action_button = direct_buttons[0]
                        button_text = action_button.text.strip()
                        button_class = action_button.get_attribute('class') or ''
                        print(f"   直接找到button: '{button_text}' (class: {button_class})")

                if not action_button:
                    print("❌ 未找到操作按钮")
                    return False

                button_text = action_button.text.strip()
                button_class = action_button.get_attribute('class')
                print(f"   最终选择的按钮: '{button_text}' (class: {button_class})")

                # 点击操作按钮
                self.driver.execute_script("arguments[0].click();", action_button)
                print("✅ 成功点击操作按钮")
                time.sleep(2)  # 等待下拉菜单出现

            except Exception as e:
                print(f"❌ 点击操作按钮失败: {e}")
                return False

            # 4. 在下拉菜单中找到"一件填充"选项并点击
            try:
                print("🔍 查找下拉菜单中的'一件填充'选项...")

                # 等待下拉菜单出现
                time.sleep(3)  # 等待下拉菜单完全加载

                # 按照用户提供的精确路径查找正确的下拉框
                print("🔍 按照精确路径查找正确的下拉框...")

                # 第一步：查找 class="jx-popper is-pure is-light jx-dropdown__popper" 的 div
                correct_dropdown = None
                try:
                    popper_elements = self.driver.find_elements(By.CSS_SELECTOR, ".jx-popper.is-pure.is-light.jx-dropdown__popper")
                    print(f"   找到 {len(popper_elements)} 个jx-dropdown__popper元素")

                    for i, popper in enumerate(popper_elements):
                        if popper.is_displayed():
                            placement = popper.get_attribute('data-popper-placement')
                            class_name = popper.get_attribute('class')
                            print(f"   popper{i+1}: placement='{placement}', class='{class_name}'")

                            # 接受 bottom 或 top placement（因为位置可能会动态调整）
                            if placement in ['bottom', 'top']:
                                correct_dropdown = popper
                                print(f"✅ 找到正确的下拉框: popper{i+1} (placement: {placement})")
                                break

                    if not correct_dropdown:
                        print("❌ 未找到合适的下拉框")
                        # 如果没找到，尝试选择最新出现的可见下拉框
                        for i, popper in enumerate(popper_elements):
                            if popper.is_displayed():
                                correct_dropdown = popper
                                placement = popper.get_attribute('data-popper-placement')
                                print(f"⚠️ 使用备选下拉框: popper{i+1} (placement: {placement})")
                                break

                    if not correct_dropdown:
                        print("❌ 未找到任何可见的下拉框")
                        return False

                except Exception as e:
                    print(f"❌ 查找jx-dropdown__popper失败: {e}")
                    return False

                # 第二步：在下拉框中按照路径查找ul
                print("🔍 按照路径查找ul元素...")

                try:
                    # class=jx-scrollbar 的 div
                    scrollbar_div = correct_dropdown.find_element(By.CSS_SELECTOR, ".jx-scrollbar")
                    print("   ✅ 找到jx-scrollbar div")

                    # class=jx-scrollbar__wrap jx-scrollbar__wrap--hidden-default 的 div
                    scrollbar_wrap = scrollbar_div.find_element(By.CSS_SELECTOR, ".jx-scrollbar__wrap.jx-scrollbar__wrap--hidden-default")
                    print("   ✅ 找到jx-scrollbar__wrap div")

                    # class=jx-scrollbar__view jx-dropdown__list 的 div
                    scrollbar_view = scrollbar_wrap.find_element(By.CSS_SELECTOR, ".jx-scrollbar__view.jx-dropdown__list")
                    print("   ✅ 找到jx-scrollbar__view div")

                    # ul 元素
                    ul_element = scrollbar_view.find_element(By.TAG_NAME, "ul")
                    print("   ✅ 找到ul元素")

                    # ul 下的所有 li 元素
                    li_elements = ul_element.find_elements(By.TAG_NAME, "li")
                    print(f"   ✅ 在ul中找到 {len(li_elements)} 个li选项")

                except Exception as e:
                    print(f"❌ 按照路径查找ul失败: {e}")
                    return False

                # 调试：显示所有选项，尝试多种方式获取文本
                print("🔍 调试：所有菜单选项:")
                for i, li in enumerate(li_elements):
                    li_text = li.text.strip()

                    # 如果直接获取的文本为空，尝试其他方法
                    if not li_text:
                        try:
                            # 方法1：获取innerHTML并提取文本
                            inner_html = li.get_attribute('innerHTML')
                            if inner_html:
                                import re
                                li_text = re.sub(r'<[^>]+>', '', inner_html).strip()

                            # 方法2：获取子元素的文本
                            if not li_text:
                                child_elements = li.find_elements(By.XPATH, ".//*")
                                for child in child_elements:
                                    child_text = child.text.strip()
                                    if child_text:
                                        li_text = child_text
                                        break

                            # 方法3：获取data属性
                            if not li_text:
                                data_value = li.get_attribute('data-value') or li.get_attribute('value')
                                if data_value:
                                    li_text = f"[{data_value}]"

                        except:
                            pass

                    print(f"   li{i+1}: '{li_text}'")

                    # 额外调试：显示li的HTML结构
                    if i < 2:  # 只显示前2个的详细结构
                        try:
                            outer_html = li.get_attribute('outerHTML')[:200] + "..." if len(li.get_attribute('outerHTML')) > 200 else li.get_attribute('outerHTML')
                            print(f"      HTML: {outer_html}")
                        except:
                            pass

                # 查找"一件填充"选项
                def get_li_text_enhanced(li_element):
                    """增强版获取li元素文本的方法"""
                    try:
                        # 方法1：直接获取text
                        text = li_element.text.strip()
                        if text:
                            return text

                        # 方法2：获取innerHTML并提取文本
                        inner_html = li_element.get_attribute('innerHTML')
                        if inner_html:
                            import re
                            text = re.sub(r'<[^>]+>', '', inner_html).strip()
                            if text:
                                return text

                        # 方法3：获取子元素的文本
                        child_elements = li_element.find_elements(By.XPATH, ".//*")
                        for child in child_elements:
                            child_text = child.text.strip()
                            if child_text:
                                return child_text

                        # 方法4：获取特定属性
                        for attr in ['data-value', 'value', 'title', 'aria-label']:
                            attr_value = li_element.get_attribute(attr)
                            if attr_value:
                                return attr_value

                        return ""
                    except:
                        return ""

                # 查找"一键填充"选项
                target_li = None

                print("🔍 调试：所有li选项内容:")
                for i, li in enumerate(li_elements):
                    li_text = get_li_text_enhanced(li)
                    li_html = li.get_attribute('outerHTML')[:200] + "..." if len(li.get_attribute('outerHTML')) > 200 else li.get_attribute('outerHTML')
                    print(f"   li{i+1}: '{li_text}'")
                    print(f"      HTML: {li_html}")

                # 查找"一键填充"选项（注意是"一键"不是"一件"）
                for li in li_elements:
                    li_text = get_li_text_enhanced(li)
                    print(f"   🔍 检查选项: '{li_text}'")
                    if "一键填充" in li_text:
                        target_li = li
                        print(f"✅ 找到'一键填充'选项: {li_text}")
                        break

                # 如果没找到"一键填充"，尝试查找其他可能的关键词
                if not target_li:
                    print("❌ 未找到'一键填充'选项，尝试其他关键词...")

                    keywords = ["一件填充", "填充", "一键", "批量填充", "自动填充"]
                    for keyword in keywords:
                        for li in li_elements:
                            li_text = get_li_text_enhanced(li)
                            if keyword in li_text:
                                target_li = li
                                print(f"✅ 找到包含'{keyword}'的选项: {li_text}")
                                break
                        if target_li:
                            break

                if not target_li:
                    print("❌ 仍未找到'一键填充'或相关选项")
                    print("🔍 当前下拉菜单中的所有选项:")
                    for i, li in enumerate(li_elements):
                        li_text = get_li_text_enhanced(li)
                        print(f"   选项{i+1}: '{li_text}'")
                    return False

                # 点击"一件填充"选项
                self.driver.execute_script("arguments[0].click();", target_li)
                print("✅ 成功点击'一件填充'选项")
                time.sleep(5)  # 增加等待时间，确保对话框完全出现

            except Exception as e:
                print(f"❌ 查找或点击'一件填充'选项失败: {e}")
                return False

            # 5. 在对话框中找到footer下的第二个button并点击
            try:
                print("🔍 查找填充对话框...")

                # 等待对话框出现，使用更宽泛的等待策略
                time.sleep(3)  # 先等待一下让对话框完全加载

                # 尝试多种方式查找对话框
                dialog = None

                # 方法1：精确匹配
                try:
                    dialog = self.driver.find_element(By.CSS_SELECTOR, ".jx-dialog.pro-dialog.pro-dialog-footer-align-right.has-header.has-footer")
                    if dialog.is_displayed():
                        print("✅ 方法1：找到精确匹配的填充对话框")
                    else:
                        dialog = None
                except:
                    pass

                # 方法2：查找任何可见的jx-dialog，但排除主创建产品对话框
                if not dialog:
                    try:
                        all_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-dialog")
                        print(f"🔍 方法2：页面上找到 {len(all_dialogs)} 个jx-dialog元素")
                        for i, d in enumerate(all_dialogs):
                            if d.is_displayed():
                                class_name = d.get_attribute('class')
                                print(f"   dialog{i+1}: {class_name}")
                                # 排除主创建产品对话框，查找新出现的对话框
                                if ('pro-dialog' in class_name and
                                    'collect-box-editor-dialog' not in class_name and
                                    'pddkj-collect-box-edit-dialog' not in class_name):
                                    # 检查这个对话框是否有footer和按钮
                                    try:
                                        test_footer = d.find_element(By.TAG_NAME, "footer")
                                        test_buttons = test_footer.find_elements(By.TAG_NAME, "button")
                                        if len(test_buttons) > 0:
                                            dialog = d
                                            print(f"✅ 方法2：选择dialog{i+1}作为填充对话框（有{len(test_buttons)}个按钮）")
                                            break
                                    except:
                                        continue
                    except:
                        pass

                # 方法3：查找任何包含footer的对话框
                if not dialog:
                    try:
                        overlay_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                        print(f"🔍 方法3：页面上找到 {len(overlay_dialogs)} 个jx-overlay-dialog元素")
                        for i, d in enumerate(overlay_dialogs):
                            if d.is_displayed():
                                try:
                                    footer_test = d.find_element(By.TAG_NAME, "footer")
                                    if footer_test:
                                        dialog = d
                                        print(f"✅ 方法3：选择overlay-dialog{i+1}作为填充对话框")
                                        break
                                except:
                                    continue
                    except:
                        pass

                # 方法4：查找最新出现的对话框
                if not dialog:
                    try:
                        wait = WebDriverWait(self.driver, 5)
                        dialog = wait.until(
                            lambda driver: driver.find_elements(By.CSS_SELECTOR, "[class*='dialog']")[-1]
                            if driver.find_elements(By.CSS_SELECTOR, "[class*='dialog']") else None
                        )
                        if dialog and dialog.is_displayed():
                            print("✅ 方法4：找到最新的对话框")
                        else:
                            dialog = None
                    except:
                        pass

                if not dialog:
                    print("❌ 未找到任何填充对话框")
                    return False

                print("✅ 找到填充对话框")

                # 查找footer
                footer = None
                try:
                    footer = dialog.find_element(By.TAG_NAME, "footer")
                    print("✅ 找到对话框footer")
                except:
                    # 如果直接找不到footer，尝试在子元素中查找
                    try:
                        footer = dialog.find_element(By.CSS_SELECTOR, "[class*='footer']")
                        print("✅ 通过class找到对话框footer")
                    except:
                        print("❌ 未找到对话框footer")
                        return False

                # 查找footer中的所有button
                footer_buttons = footer.find_elements(By.TAG_NAME, "button")
                print(f"   footer中找到 {len(footer_buttons)} 个按钮")

                # 调试：显示所有按钮
                print("🔍 调试：footer中的所有按钮:")
                for i, btn in enumerate(footer_buttons):
                    btn_text = btn.text.strip()
                    btn_class = btn.get_attribute('class')
                    print(f"   button{i+1}: '{btn_text}' (class: {btn_class})")

                if len(footer_buttons) < 2:
                    print("❌ footer中按钮数量不足")
                    # 如果只有一个按钮，检查是否是确认按钮
                    if len(footer_buttons) == 1:
                        btn_text = footer_buttons[0].text.strip()
                        if any(keyword in btn_text for keyword in ['确定', '确认', '提交', '保存']):
                            print(f"⚠️ 只有一个按钮，但是确认按钮，尝试点击: {btn_text}")
                            self.driver.execute_script("arguments[0].click();", footer_buttons[0])
                            print(f"✅ 成功点击确认按钮: {btn_text}")
                            time.sleep(3)
                            return True
                    return False

                # 点击第二个按钮
                second_button = footer_buttons[1]
                second_button_text = second_button.text.strip()
                print(f"🖱️ 准备点击第二个按钮: '{second_button_text}'")

                self.driver.execute_script("arguments[0].click();", second_button)
                print(f"✅ 成功点击第二个按钮: '{second_button_text}'")
                time.sleep(3)  # 等待填充完成

                return True

            except Exception as e:
                print(f"❌ 查找或点击对话框按钮失败: {e}")
                import traceback
                traceback.print_exc()
                return False

        except Exception as e:
            print(f"❌ 填充SKU预览图失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def batch_modify_supply_price(self, supply_price):
        """批量修改供货价"""
        try:
            print(f"💰 开始批量修改供货价: {supply_price}")

            # 1. 找到 pro-virtual-table__header div下的第五个 div下的 button
            try:
                print("🔍 查找供货价批量修改按钮...")

                # 重新找到表格头部容器（确保元素是最新的）
                sku_property_list = self.driver.find_element(By.CSS_SELECTOR, ".sku-property-list")
                parent = sku_property_list.find_element(By.XPATH, "..")
                sibling_divs = parent.find_elements(By.XPATH, "./div")
                last_sibling_div = sibling_divs[-1]
                last_div_children = last_sibling_div.find_elements(By.XPATH, "./div")
                second_div = last_div_children[1]
                second_div_children = second_div.find_elements(By.XPATH, "./div")
                third_div = second_div_children[2]
                third_div_children = third_div.find_elements(By.XPATH, "./div")
                first_div_level4 = third_div_children[0]
                level4_children = first_div_level4.find_elements(By.XPATH, "./div")
                first_div_level5 = level4_children[0]
                level5_children = first_div_level5.find_elements(By.XPATH, "./div")
                table_header = level5_children[0]

                print("✅ 重新找到表格头部容器")

                # 找到第五个div
                header_divs = table_header.find_elements(By.XPATH, "./div")
                print(f"   表格头部找到 {len(header_divs)} 个div")

                if len(header_divs) < 5:
                    print("❌ 表格头部div数量不足")
                    return False

                fifth_div = header_divs[4]  # 第五个div（索引4）
                fifth_div_class = fifth_div.get_attribute('class') or ''
                fifth_div_text = fifth_div.text.strip()
                print(f"   第五个div: class='{fifth_div_class}', text='{fifth_div_text}'")

                # 在第五个div下查找button
                supply_price_button = None
                try:
                    supply_price_button = fifth_div.find_element(By.TAG_NAME, "button")
                    print("✅ 在第五个div下直接找到button")
                except:
                    # 如果直接找不到，在子div中查找
                    child_divs = fifth_div.find_elements(By.TAG_NAME, "div")
                    for i, child_div in enumerate(child_divs):
                        buttons = child_div.find_elements(By.TAG_NAME, "button")
                        if buttons:
                            supply_price_button = buttons[0]
                            print(f"✅ 在第五个div的子div{i+1}中找到button")
                            break

                if not supply_price_button:
                    print("❌ 未找到供货价批量修改按钮")
                    return False

                button_text = supply_price_button.text.strip()
                button_class = supply_price_button.get_attribute('class')
                print(f"   找到供货价按钮: '{button_text}' (class: {button_class})")

                # 点击供货价按钮
                self.driver.execute_script("arguments[0].click();", supply_price_button)
                print("✅ 成功点击供货价批量修改按钮")
                time.sleep(2)  # 等待对话框出现

            except Exception as e:
                print(f"❌ 查找或点击供货价按钮失败: {e}")
                return False

            # 2. 查找批量修改供货价对话框
            try:
                print("🔍 查找批量修改供货价对话框...")

                # 等待对话框出现
                wait = WebDriverWait(self.driver, 10)
                price_dialog = wait.until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".jx-overlay-dialog[aria-label='批量修改供货价']"))
                )
                print("✅ 找到批量修改供货价对话框")

                # 确保对话框可见
                if not price_dialog.is_displayed():
                    print("⚠️ 对话框存在但不可见，等待...")
                    time.sleep(2)

            except Exception as e:
                print(f"❌ 未找到批量修改供货价对话框: {e}")
                # 调试：查找所有可能的对话框
                try:
                    all_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                    print(f"🔍 调试：页面上找到 {len(all_dialogs)} 个jx-overlay-dialog元素")
                    for i, dialog in enumerate(all_dialogs):
                        if dialog.is_displayed():
                            aria_label = dialog.get_attribute('aria-label') or ''
                            class_name = dialog.get_attribute('class')
                            print(f"   dialog{i+1}: aria-label='{aria_label}', class='{class_name}'")
                except:
                    pass
                return False

            # 3. 在对话框中找到第二个form下的input并输入供货价
            try:
                print("🔍 在对话框中查找供货价输入框...")

                # 查找所有form元素
                forms = price_dialog.find_elements(By.TAG_NAME, "form")
                print(f"   对话框中找到 {len(forms)} 个form元素")

                if len(forms) < 2:
                    print("❌ 对话框中form数量不足")
                    return False

                second_form = forms[1]  # 第二个form
                print("   选择第二个form")

                # 在第二个form下找到第一个div
                form_divs = second_form.find_elements(By.XPATH, "./div")
                print(f"   第二个form下找到 {len(form_divs)} 个div")

                if len(form_divs) < 1:
                    print("❌ 第二个form下没有div")
                    return False

                first_div = form_divs[0]  # 第一个div
                print("   选择第一个div")

                # 在第一个div下找到div
                first_div_children = first_div.find_elements(By.XPATH, "./div")
                print(f"   第一个div下找到 {len(first_div_children)} 个子div")

                if len(first_div_children) < 1:
                    print("❌ 第一个div下没有子div")
                    return False

                target_div = first_div_children[0]  # 第一个子div
                print("   选择第一个子div")

                # 递归查找input
                price_input = None

                # 方法1：直接在目标div下查找input
                inputs = target_div.find_elements(By.TAG_NAME, "input")
                if inputs:
                    price_input = inputs[0]
                    print("   方法1成功：直接找到input")

                # 方法2：递归查找input
                if not price_input:
                    all_inputs = target_div.find_elements(By.XPATH, ".//input")
                    if all_inputs:
                        price_input = all_inputs[0]
                        print("   方法2成功：递归找到input")

                if not price_input:
                    print("❌ 未找到供货价输入框")
                    return False

                input_type = price_input.get_attribute('type') or ''
                input_class = price_input.get_attribute('class') or ''
                input_placeholder = price_input.get_attribute('placeholder') or ''
                print(f"   找到供货价输入框: type='{input_type}', class='{input_class}', placeholder='{input_placeholder}'")

                # 清空并输入供货价
                price_input.clear()
                price_input.send_keys(str(supply_price))
                print(f"✅ 成功输入供货价: {supply_price}")
                time.sleep(1)

            except Exception as e:
                print(f"❌ 查找或输入供货价失败: {e}")
                return False

            # 4. 找到footer下的第二个按钮并点击
            try:
                print("🔍 查找对话框footer中的确认按钮...")

                # 在对话框中查找footer
                footer = price_dialog.find_element(By.TAG_NAME, "footer")
                print("✅ 找到对话框footer")

                # 查找footer中的所有button
                footer_buttons = footer.find_elements(By.TAG_NAME, "button")
                print(f"   footer中找到 {len(footer_buttons)} 个按钮")

                # 调试：显示所有按钮
                print("🔍 调试：footer中的所有按钮:")
                for i, btn in enumerate(footer_buttons):
                    btn_text = btn.text.strip()
                    btn_class = btn.get_attribute('class')
                    print(f"   button{i+1}: '{btn_text}' (class: {btn_class})")

                if len(footer_buttons) < 2:
                    print("❌ footer中按钮数量不足")
                    return False

                # 点击第二个按钮
                second_button = footer_buttons[1]
                second_button_text = second_button.text.strip()
                print(f"🖱️ 准备点击第二个按钮: '{second_button_text}'")

                self.driver.execute_script("arguments[0].click();", second_button)
                print(f"✅ 成功点击第二个按钮: '{second_button_text}'")
                time.sleep(2)  # 等待修改完成

                return True

            except Exception as e:
                print(f"❌ 查找或点击确认按钮失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 批量修改供货价失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def batch_modify_suggested_price(self, suggested_price):
        """批量修改建议售价"""
        try:
            print(f"💰 开始批量修改建议售价: {suggested_price}")

            # 1. 找到 pro-virtual-table__header div下的第六个 div下的 button
            try:
                print("🔍 查找建议售价批量修改按钮...")

                # 重新找到表格头部容器（确保元素是最新的）
                sku_property_list = self.driver.find_element(By.CSS_SELECTOR, ".sku-property-list")
                parent = sku_property_list.find_element(By.XPATH, "..")
                sibling_divs = parent.find_elements(By.XPATH, "./div")
                last_sibling_div = sibling_divs[-1]
                last_div_children = last_sibling_div.find_elements(By.XPATH, "./div")
                second_div = last_div_children[1]
                second_div_children = second_div.find_elements(By.XPATH, "./div")
                third_div = second_div_children[2]
                third_div_children = third_div.find_elements(By.XPATH, "./div")
                first_div_level4 = third_div_children[0]
                level4_children = first_div_level4.find_elements(By.XPATH, "./div")
                first_div_level5 = level4_children[0]
                level5_children = first_div_level5.find_elements(By.XPATH, "./div")
                table_header = level5_children[0]

                print("✅ 重新找到表格头部容器")

                # 找到第六个div
                header_divs = table_header.find_elements(By.XPATH, "./div")
                print(f"   表格头部找到 {len(header_divs)} 个div")

                if len(header_divs) < 6:
                    print("❌ 表格头部div数量不足")
                    return False

                sixth_div = header_divs[5]  # 第六个div（索引5）
                sixth_div_class = sixth_div.get_attribute('class') or ''
                sixth_div_text = sixth_div.text.strip()
                print(f"   第六个div: class='{sixth_div_class}', text='{sixth_div_text}'")

                # 在第六个div下查找button
                suggested_price_button = None
                try:
                    suggested_price_button = sixth_div.find_element(By.TAG_NAME, "button")
                    print("✅ 在第六个div下直接找到button")
                except:
                    # 如果直接找不到，在子div中查找
                    child_divs = sixth_div.find_elements(By.TAG_NAME, "div")
                    for i, child_div in enumerate(child_divs):
                        buttons = child_div.find_elements(By.TAG_NAME, "button")
                        if buttons:
                            suggested_price_button = buttons[0]
                            print(f"✅ 在第六个div的子div{i+1}中找到button")
                            break

                if not suggested_price_button:
                    print("❌ 未找到建议售价批量修改按钮")
                    return False

                button_text = suggested_price_button.text.strip()
                button_class = suggested_price_button.get_attribute('class')
                print(f"   找到建议售价按钮: '{button_text}' (class: {button_class})")

                # 点击建议售价按钮
                self.driver.execute_script("arguments[0].click();", suggested_price_button)
                print("✅ 成功点击建议售价批量修改按钮")
                time.sleep(2)  # 等待对话框出现

            except Exception as e:
                print(f"❌ 查找或点击建议售价按钮失败: {e}")
                return False

            # 2. 查找批量修改建议售价对话框
            try:
                print("🔍 查找批量修改建议售价对话框...")

                # 等待对话框出现
                wait = WebDriverWait(self.driver, 10)
                price_dialog = wait.until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".jx-overlay-dialog[aria-label='批量修改建议售价']"))
                )
                print("✅ 找到批量修改建议售价对话框")

                # 确保对话框可见
                if not price_dialog.is_displayed():
                    print("⚠️ 对话框存在但不可见，等待...")
                    time.sleep(2)

            except Exception as e:
                print(f"❌ 未找到批量修改建议售价对话框: {e}")
                # 调试：查找所有可能的对话框
                try:
                    all_dialogs = self.driver.find_elements(By.CSS_SELECTOR, ".jx-overlay-dialog")
                    print(f"🔍 调试：页面上找到 {len(all_dialogs)} 个jx-overlay-dialog元素")
                    for i, dialog in enumerate(all_dialogs):
                        if dialog.is_displayed():
                            aria_label = dialog.get_attribute('aria-label') or ''
                            class_name = dialog.get_attribute('class')
                            print(f"   dialog{i+1}: aria-label='{aria_label}', class='{class_name}'")
                except:
                    pass
                return False

            # 3. 在对话框中找到第二个form下的input并输入建议售价
            try:
                print("🔍 在对话框中查找建议售价输入框...")
                print("🔍 按照精确路径：对话框 -> 第二个form -> 第一个div -> div -> 递归找input")

                # 查找所有form元素
                forms = price_dialog.find_elements(By.TAG_NAME, "form")
                print(f"   对话框中找到 {len(forms)} 个form元素")

                if len(forms) < 2:
                    print("❌ 对话框中form数量不足")
                    return False

                second_form = forms[1]  # 第二个form
                second_form_class = second_form.get_attribute('class') or ''
                print(f"   选择第二个form: class='{second_form_class}'")

                # 在第二个form下找到第一个div
                form_divs = second_form.find_elements(By.XPATH, "./div")
                print(f"   第二个form下找到 {len(form_divs)} 个直接子div")

                if len(form_divs) < 1:
                    print("❌ 第二个form下没有div")
                    return False

                first_div = form_divs[0]  # 第一个div
                first_div_class = first_div.get_attribute('class') or ''
                print(f"   选择第一个div: class='{first_div_class}'")

                # 在第一个div下找到div（跳过label div，找到包含input的div）
                first_div_children = first_div.find_elements(By.XPATH, "./div")
                print(f"   第一个div下找到 {len(first_div_children)} 个直接子div")

                # 调试：显示所有子div
                for i, child_div in enumerate(first_div_children):
                    child_class = child_div.get_attribute('class') or ''
                    print(f"   子div{i+1}: class='{child_class}'")

                # 查找不是label的div（通常是第二个div，包含实际的输入控件）
                target_div = None
                for child_div in first_div_children:
                    child_class = child_div.get_attribute('class') or ''
                    if 'label' not in child_class:  # 跳过label div
                        target_div = child_div
                        print(f"   ✅ 选择非label的div: class='{child_class}'")
                        break

                if not target_div:
                    print("❌ 未找到包含输入控件的div")
                    return False

                # 递归查找input，专门查找 class=jx-input__inner 的input
                price_input = None

                # 方法1：专门查找 class=jx-input__inner 的input
                jx_input_inner = target_div.find_elements(By.XPATH, ".//input[contains(@class, 'jx-input__inner')]")
                print(f"   在目标div中找到 {len(jx_input_inner)} 个jx-input__inner元素")

                if jx_input_inner:
                    price_input = jx_input_inner[0]
                    input_class = price_input.get_attribute('class') or ''
                    input_placeholder = price_input.get_attribute('placeholder') or ''
                    print(f"   ✅ 方法1成功：找到jx-input__inner输入框: class='{input_class}', placeholder='{input_placeholder}'")

                # 方法2：如果没找到jx-input__inner，查找所有input并调试
                if not price_input:
                    all_inputs = target_div.find_elements(By.XPATH, ".//input")
                    print(f"   方法1未找到，在目标div中找到 {len(all_inputs)} 个input元素")

                    for i, inp in enumerate(all_inputs):
                        input_type = inp.get_attribute('type') or ''
                        input_class = inp.get_attribute('class') or ''
                        input_placeholder = inp.get_attribute('placeholder') or ''
                        print(f"   input{i+1}: type='{input_type}', class='{input_class}', placeholder='{input_placeholder}'")

                        # 查找文本输入框（排除radio、checkbox等）
                        if input_type in ['text', 'number', ''] and 'radio' not in input_class and 'checkbox' not in input_class:
                            price_input = inp
                            print(f"   ✅ 方法2选择input{i+1}作为建议售价输入框")
                            break

                # 方法2：如果没找到合适的input，查找其他可能的输入元素
                if not price_input:
                    print("   方法1未找到合适的input，尝试查找其他输入元素...")

                    # 查找所有可能的输入元素
                    possible_inputs = []
                    possible_inputs.extend(target_div.find_elements(By.XPATH, ".//input[@type='text']"))
                    possible_inputs.extend(target_div.find_elements(By.XPATH, ".//input[@type='number']"))
                    possible_inputs.extend(target_div.find_elements(By.XPATH, ".//input[not(@type)]"))

                    if possible_inputs:
                        price_input = possible_inputs[0]
                        print(f"   ✅ 方法2找到输入框: type='{price_input.get_attribute('type')}'")

                # 方法3：在整个对话框中查找价格输入框
                if not price_input:
                    print("   方法2未找到，在整个对话框中查找价格输入框...")

                    # 查找包含价格相关placeholder的输入框
                    price_inputs = price_dialog.find_elements(By.XPATH, ".//input[contains(@placeholder, '价格') or contains(@placeholder, '金额') or contains(@placeholder, '元')]")
                    if price_inputs:
                        price_input = price_inputs[0]
                        print(f"   ✅ 方法3找到价格输入框: placeholder='{price_input.get_attribute('placeholder')}'")

                # 方法4：查找所有可能的文本输入框
                if not price_input:
                    print("   方法3未找到，查找所有可能的文本输入框...")

                    all_text_inputs = price_dialog.find_elements(By.XPATH, ".//input[@type='text' or @type='number' or not(@type)]")
                    print(f"   在对话框中找到 {len(all_text_inputs)} 个可能的文本输入框")

                    for i, inp in enumerate(all_text_inputs):
                        inp_class = inp.get_attribute('class') or ''
                        inp_placeholder = inp.get_attribute('placeholder') or ''
                        inp_type = inp.get_attribute('type') or ''
                        print(f"   文本输入框{i+1}: type='{inp_type}', class='{inp_class}', placeholder='{inp_placeholder}'")

                        # 排除radio和checkbox
                        if 'radio' not in inp_class and 'checkbox' not in inp_class:
                            price_input = inp
                            print(f"   ✅ 方法4选择文本输入框{i+1}")
                            break

                # 方法5：如果建议售价对话框是选择型的，尝试处理radio选项
                if not price_input:
                    print("   方法4未找到文本输入框，检查是否为选择型对话框...")

                    # 查找所有radio按钮
                    radio_inputs = price_dialog.find_elements(By.XPATH, ".//input[@type='radio']")
                    print(f"   找到 {len(radio_inputs)} 个radio按钮")

                    if radio_inputs:
                        print("   ⚠️ 建议售价对话框似乎是选择型的，而不是输入型的")
                        print("   💡 可能需要选择预设的价格选项，而不是直接输入价格")

                        # 查找是否有自定义输入选项
                        custom_inputs = price_dialog.find_elements(By.XPATH, ".//input[contains(@placeholder, '自定义') or contains(@placeholder, '输入')]")
                        if custom_inputs:
                            price_input = custom_inputs[0]
                            print(f"   ✅ 找到自定义输入框: placeholder='{price_input.get_attribute('placeholder')}'")
                        else:
                            print("   ❌ 未找到自定义输入选项")
                            return False

                if not price_input:
                    print("❌ 未找到建议售价输入框")
                    return False

                input_type = price_input.get_attribute('type') or ''
                input_class = price_input.get_attribute('class') or ''
                input_placeholder = price_input.get_attribute('placeholder') or ''
                print(f"   最终选择的建议售价输入框: type='{input_type}', class='{input_class}', placeholder='{input_placeholder}'")

                # 清空并输入建议售价
                try:
                    price_input.clear()
                    price_input.send_keys(str(suggested_price))
                    print(f"✅ 成功输入建议售价: {suggested_price}")
                    time.sleep(1)
                except Exception as input_error:
                    print(f"❌ 输入建议售价失败: {input_error}")
                    return False

            except Exception as e:
                print(f"❌ 查找或输入建议售价失败: {e}")
                return False

            # 4. 找到footer下的第二个按钮并点击
            try:
                print("🔍 查找对话框footer中的确认按钮...")

                # 在对话框中查找footer
                footer = price_dialog.find_element(By.TAG_NAME, "footer")
                print("✅ 找到对话框footer")

                # 查找footer中的所有button
                footer_buttons = footer.find_elements(By.TAG_NAME, "button")
                print(f"   footer中找到 {len(footer_buttons)} 个按钮")

                # 调试：显示所有按钮
                print("🔍 调试：footer中的所有按钮:")
                for i, btn in enumerate(footer_buttons):
                    btn_text = btn.text.strip()
                    btn_class = btn.get_attribute('class')
                    print(f"   button{i+1}: '{btn_text}' (class: {btn_class})")

                if len(footer_buttons) < 2:
                    print("❌ footer中按钮数量不足")
                    return False

                # 点击第二个按钮
                second_button = footer_buttons[1]
                second_button_text = second_button.text.strip()
                print(f"🖱️ 准备点击第二个按钮: '{second_button_text}'")

                self.driver.execute_script("arguments[0].click();", second_button)
                print(f"✅ 成功点击第二个按钮: '{second_button_text}'")
                time.sleep(2)  # 等待修改完成

                return True

            except Exception as e:
                print(f"❌ 查找或点击确认按钮失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 批量修改建议售价失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def upload_to_file_input(self, file_input, image_files, image_dir):
        """使用指定的文件输入框上传图片"""
        try:
            print(f"📤 使用文件输入框上传 {len(image_files)} 张图片...")

            # 准备图片文件路径
            file_paths = []
            for image_file in image_files:
                abs_path = os.path.abspath(image_file)
                if os.path.exists(abs_path):
                    file_paths.append(abs_path)
                    print(f"   ✅ 准备上传: {os.path.basename(image_file)}")
                else:
                    print(f"   ❌ 文件不存在: {os.path.basename(image_file)}")

            if not file_paths:
                print("❌ 没有有效的图片文件")
                return False

            # 尝试上传第一张图片
            try:
                first_file = file_paths[0]
                print(f"🎯 上传第一张图片: {os.path.basename(first_file)}")
                file_input.send_keys(first_file)
                print("✅ 第一张图片上传命令已发送")
                time.sleep(3)

                # 检查是否成功
                carousel_check = self.check_carousel_images()
                if carousel_check:
                    print("✅ 检测到轮播图有图片，上传成功！")
                    return True
                else:
                    print("⚠️ 轮播图暂无变化，继续尝试...")

            except Exception as e:
                print(f"❌ 上传失败: {e}")
                return False

            return False

        except Exception as e:
            print(f"❌ 文件上传过程失败: {e}")
            return False

    def check_carousel_images(self):
        """检查轮播图是否有图片"""
        try:
            # 查找轮播图中的图片元素
            carousel_selectors = [
                "img[src*='blob:']",  # blob URL图片
                "img[src*='data:']",  # data URL图片
                ".carousel-image",    # 轮播图图片
                ".product-image",     # 产品图片
                ".upload-preview img", # 上传预览图片
                ".image-item img",    # 图片项
                "[class*='image'] img", # 包含image的class
                ".jx-image img",      # jx-image组件
            ]

            total_images = 0
            for selector in carousel_selectors:
                images = self.driver.find_elements(By.CSS_SELECTOR, selector)
                if images:
                    print(f"🔍 选择器 '{selector}' 找到 {len(images)} 张图片")
                    total_images += len(images)

            print(f"📸 轮播图区域总共检测到 {total_images} 张图片")
            return total_images > 0

        except Exception as e:
            print(f"❌ 检查轮播图失败: {e}")
            return False

    def process_single_product_data(self, product_data):
        """
        处理单个产品数据

        Args:
            product_data: 单个产品的数据字典

        Returns:
            bool: 处理是否成功
        """
        try:
            print(f"📦 开始处理产品: {product_data.get('产品标题:', '')[:50]}...")

            # 创建产品数据对象
            temp_product_data = ProductData()
            temp_product_data.products = [product_data]
            self.product_data = temp_product_data

            # 处理登录后的弹窗
            print("🔧 处理登录后弹窗...")
            self.handle_popups()

            # 查找并点击创建产品按钮
            print("🔧 查找创建产品按钮...")
            if self.click_create_product():
                print("✅ 产品创建弹窗已打开")

                # 批量创建产品（实际只创建一个）
                print("🔧 开始创建产品...")
                success = self.batch_create_products()

                if success:
                    print(f"✅ 产品处理成功: {product_data.get('产品标题:', '')[:50]}")
                    return True
                else:
                    print(f"❌ 产品处理失败: {product_data.get('产品标题:', '')[:50]}")
                    return False
            else:
                print("❌ 未能打开产品创建弹窗")
                return False

        except Exception as e:
            print(f"❌ 处理单个产品时出错: {e}")
            return False

    def find_and_click_create_product_button(self):
        """寻找并点击创建产品按钮"""
        try:
            print("🔍 寻找创建产品按钮...")

            # 等待页面加载
            time.sleep(2)

            # 尝试多种可能的创建产品按钮选择器
            create_button_selectors = [
                "//button[contains(text(), '创建产品')]",
                "//a[contains(text(), '创建产品')]",
                "//span[contains(text(), '创建产品')]",
                "//button[contains(@class, 'create') and contains(text(), '产品')]",
                "//a[contains(@class, 'create') and contains(text(), '产品')]",
                ".create-product-btn",
                "#create-product",
                "button[data-action='create-product']"
            ]

            for selector in create_button_selectors:
                try:
                    if selector.startswith("//"):
                        # XPath选择器
                        elements = self.driver.find_elements(By.XPATH, selector)
                    else:
                        # CSS选择器
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)

                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            print(f"✅ 找到创建产品按钮: {element.text}")
                            try:
                                element.click()
                                print("✅ 成功点击创建产品按钮")
                                return True
                            except:
                                # 尝试JavaScript点击
                                self.driver.execute_script("arguments[0].click();", element)
                                print("✅ 使用JavaScript点击创建产品按钮")
                                return True
                except:
                    continue

            print("❌ 未找到创建产品按钮")
            return False

        except Exception as e:
            print(f"❌ 寻找创建产品按钮时出错: {e}")
            return False

    def close_browser(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            print("🔚 浏览器已关闭")

    def batch_modify_sku_category(self):
        """批量修改SKU分类 - 在产品创建弹窗的SKU表格中执行"""
        try:
            print("🔄 开始批量修改SKU分类...")

            # 1. 首先确保我们在产品创建弹窗中，查找SKU表格
            print("🔍 查找产品创建弹窗中的SKU表格...")
            try:
                # 查找SKU表格的容器，使用更通用的方法
                sku_table_selectors = [
                    ".sku-property-list",  # SKU属性列表容器
                    ".pro-virtual-table__header",  # 虚拟表格头部
                    "[class*='sku-property']",  # 包含sku-property的元素
                ]

                table_header = None
                for selector in sku_table_selectors:
                    try:
                        # 查找所有匹配的元素
                        elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                        for element in elements:
                            # 检查元素是否包含SKU分类相关内容
                            if "SKU分类" in element.text or "批量" in element.text:
                                # 如果是sku-property-list，需要找到其中的表格头部
                                if "sku-property" in element.get_attribute("class"):
                                    # 在sku-property-list中查找pro-virtual-table__header
                                    headers = element.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__header")
                                    if headers:
                                        table_header = headers[0]
                                        print(f"✅ 在{selector}中找到SKU表格头部")
                                        break
                                else:
                                    table_header = element
                                    print(f"✅ 直接找到SKU表格头部: {selector}")
                                    break
                        if table_header:
                            break
                    except:
                        continue

                if not table_header:
                    print("❌ 未找到包含SKU分类的表格头部")
                    return False

            except Exception as e:
                print(f"❌ 查找SKU表格失败: {e}")
                return False

            # 2. 快速查找包含SKU分类的div（已知结构）
            print("🔍 快速查找SKU分类div...")
            try:
                header_divs = table_header.find_elements(By.CSS_SELECTOR, "div")

                # 直接查找包含SKU分类的div（不输出调试信息）
                sku_div = None
                for div in header_divs:
                    try:
                        if "SKU分类" in div.text:
                            sku_div = div
                            print(f"✅ 找到SKU分类div")
                            break
                    except:
                        continue

                if not sku_div:
                    print("❌ 未找到包含SKU分类的div")
                    return False

                eighth_div = sku_div  # 使用找到的SKU分类div

            except Exception as e:
                print(f"❌ 查找SKU分类div失败: {e}")
                return False

            # 3. 在SKU分类div中查找批量按钮并点击
            print("🔍 在SKU分类div中查找批量按钮...")
            try:
                # 参考成功的供货价和建议售价批量修改逻辑
                # 查找div下的button元素
                buttons = eighth_div.find_elements(By.CSS_SELECTOR, "button")

                if buttons:
                    # 选择第一个button（通常是批量按钮）
                    batch_button = buttons[0]
                    button_text = batch_button.text.strip()
                    button_class = batch_button.get_attribute("class") or ""
                    print(f"✅ 找到按钮: '{button_text}' (class: {button_class})")

                    # 点击批量按钮
                    try:
                        batch_button.click()
                        print("✅ 成功点击SKU分类批量按钮")
                    except:
                        self.driver.execute_script("arguments[0].click();", batch_button)
                        print("✅ 使用JavaScript点击SKU分类批量按钮")

                    time.sleep(3)  # 等待弹窗出现
                else:
                    # 如果直接查找button失败，尝试查找dropdown结构
                    print("🔍 未找到直接的button，尝试查找dropdown结构...")
                    dropdowns = eighth_div.find_elements(By.CSS_SELECTOR, ".jx-dropdown")

                    if dropdowns:
                        dropdown = dropdowns[0]
                        dropdown_buttons = dropdown.find_elements(By.CSS_SELECTOR, "button")

                        if dropdown_buttons:
                            batch_button = dropdown_buttons[0]
                            button_text = batch_button.text.strip()
                            print(f"✅ 在dropdown中找到按钮: '{button_text}'")

                            try:
                                batch_button.click()
                                print("✅ 成功点击dropdown中的批量按钮")
                            except:
                                self.driver.execute_script("arguments[0].click();", batch_button)
                                print("✅ 使用JavaScript点击dropdown中的批量按钮")

                            time.sleep(1)  # 快速等待弹窗出现
                        else:
                            print("❌ dropdown中未找到按钮")
                            return False
                    else:
                        print("❌ 未找到dropdown结构")
                        return False

            except Exception as e:
                print(f"❌ 查找或点击批量按钮失败: {e}")
                return False

            # 6. 等待并查找批量修改SKU分类弹窗
            print("🔍 查找批量修改SKU分类弹窗...")
            try:
                sku_dialog = WebDriverWait(self.driver, 10).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR,
                        "div.jx-overlay-dialog[aria-label='批量修改SKU分类']"))
                )

                if sku_dialog.is_displayed():
                    print("✅ 找到批量修改SKU分类弹窗")
                else:
                    print("❌ 批量修改SKU分类弹窗不可见")
                    return False
            except TimeoutException:
                print("❌ 等待批量修改SKU分类弹窗超时")
                return False
            except Exception as e:
                print(f"❌ 查找批量修改SKU分类弹窗失败: {e}")
                return False

            # 7. 递归查找class=pro-input-group sku-classification-input-group的div
            print("🔍 递归查找pro-input-group sku-classification-input-group容器...")
            try:
                input_group = self.find_element_recursively(sku_dialog,
                    "div.pro-input-group.sku-classification-input-group")

                if input_group:
                    print("✅ 找到pro-input-group sku-classification-input-group容器")
                else:
                    print("❌ 未找到pro-input-group sku-classification-input-group容器")
                    return False
            except Exception as e:
                print(f"❌ 递归查找input-group容器失败: {e}")
                return False

            # 4. 模拟点击这个div下第一个div下的第一个div
            print("🔍 查找并点击input-group下的第一个div的第一个div...")
            try:
                # 找到input-group下的第一个div（使用更安全的选择器）
                first_level_divs = input_group.find_elements(By.XPATH, "./div")
                if first_level_divs:
                    first_div = first_level_divs[0]
                    print("✅ 找到第一个div")

                    # 找到第一个div下的第一个div
                    second_level_divs = first_div.find_elements(By.XPATH, "./div")
                    if second_level_divs:
                        target_div = second_level_divs[0]
                        print("✅ 找到第一个div下的第一个div")

                        # 调试：显示目标div的信息
                        try:
                            div_class = target_div.get_attribute("class") or ""
                            div_text = target_div.text.strip()
                            print(f"🔍 目标div信息: class='{div_class}', text='{div_text[:30]}...'")
                        except:
                            pass

                        # 点击这个div
                        try:
                            target_div.click()
                            print("✅ 成功点击目标div")
                        except:
                            self.driver.execute_script("arguments[0].click();", target_div)
                            print("✅ 使用JavaScript点击目标div")

                        time.sleep(2)  # 等待下拉框出现
                    else:
                        print("❌ 第一个div下没有找到子div")
                        return False
                else:
                    print("❌ input-group下没有找到div")
                    return False
            except Exception as e:
                print(f"❌ 查找或点击目标div失败: {e}")
                return False

            return self.select_single_product_option_and_confirm(sku_dialog)

        except Exception as e:
            print(f"❌ 批量修改SKU分类失败: {e}")
            return False

    def select_single_product_option_and_confirm(self, sku_dialog):
        """选择单品选项并确认"""
        try:
            # 5. 选择"单品"选项
            print("🔍 查找并选择'单品'选项...")
            try:
                # 快速等待下拉选项出现
                time.sleep(1)

                # 快速查找并点击单品选项（已知结构）
                found_options = False

                # 直接查找最常见的下拉容器和选项
                try:
                    dropdown = self.driver.find_element(By.CSS_SELECTOR, ".jx-select-dropdown")
                    if dropdown.is_displayed():
                        li_options = dropdown.find_elements(By.CSS_SELECTOR, "li")
                        for li in li_options:
                            if li.is_displayed() and "单品" in li.text:
                                self.driver.execute_script("arguments[0].click();", li)
                                print("✅ 快速点击单品选项")
                                found_options = True
                                break
                except:
                    pass

                # 如果上面失败，尝试其他常见容器
                if not found_options:
                    for selector in [".jx-popper", "[class*='dropdown']"]:
                        try:
                            dropdowns = self.driver.find_elements(By.CSS_SELECTOR, selector)
                            for dropdown in dropdowns:
                                if dropdown.is_displayed() and "单品" in dropdown.text:
                                    li_options = dropdown.find_elements(By.CSS_SELECTOR, "li")
                                    for li in li_options:
                                        if li.is_displayed() and "单品" in li.text:
                                            self.driver.execute_script("arguments[0].click();", li)
                                            print("✅ 快速点击单品选项")
                                            found_options = True
                                            break
                                    if found_options:
                                        break
                            if found_options:
                                break
                        except:
                            continue

                if not found_options:
                    print("❌ 未找到单品选项")
                    return False

                time.sleep(1)  # 减少等待时间

            except Exception as e:
                print(f"❌ 选择单品选项失败: {e}")
                return False

            # 10. 回到弹窗，找到footer标签下的第二个按钮并点击
            print("🔍 查找footer标签下的第二个按钮...")
            try:
                # 重新获取弹窗元素（可能因为DOM更新而失效）
                sku_dialog = self.driver.find_element(By.CSS_SELECTOR,
                    "div.jx-overlay-dialog[aria-label='批量修改SKU分类']")

                # 查找footer标签
                footer = sku_dialog.find_element(By.CSS_SELECTOR, "footer")
                print("✅ 找到footer标签")

                # 查找footer下的所有按钮
                footer_buttons = footer.find_elements(By.CSS_SELECTOR, "button")

                if len(footer_buttons) >= 2:
                    second_button = footer_buttons[1]  # 第二个按钮（索引为1）
                    button_text = second_button.text.strip()
                    print(f"✅ 找到第二个按钮: '{button_text}'")

                    # 点击第二个按钮
                    try:
                        second_button.click()
                        print("✅ 成功点击第二个按钮，完成SKU分类批量修改")
                    except:
                        self.driver.execute_script("arguments[0].click();", second_button)
                        print("✅ 使用JavaScript点击第二个按钮，完成SKU分类批量修改")

                    time.sleep(3)  # 等待操作完成
                    return True
                else:
                    print(f"❌ footer下只有{len(footer_buttons)}个按钮，少于2个")
                    return False
            except Exception as e:
                print(f"❌ 查找或点击footer按钮失败: {e}")
                return False

        except Exception as e:
            print(f"❌ 选择单品选项并确认失败: {e}")
            return False

    def find_element_recursively(self, parent_element, css_selector):
        """递归查找元素"""
        try:
            # 首先尝试直接查找
            try:
                element = parent_element.find_element(By.CSS_SELECTOR, css_selector)
                if element.is_displayed():
                    return element
            except:
                pass

            # 如果直接查找失败，递归查找所有子元素
            child_elements = parent_element.find_elements(By.CSS_SELECTOR, "*")

            for child in child_elements:
                try:
                    # 检查当前子元素是否匹配
                    if self.element_matches_selector(child, css_selector):
                        if child.is_displayed():
                            return child

                    # 递归查找子元素的子元素
                    result = self.find_element_recursively(child, css_selector)
                    if result:
                        return result
                except:
                    continue

            return None
        except Exception as e:
            print(f"❌ 递归查找元素失败: {e}")
            return None

    def element_matches_selector(self, element, css_selector):
        """检查元素是否匹配CSS选择器"""
        try:
            # 解析CSS选择器（简单实现，支持class选择器）
            if css_selector.startswith("div."):
                # 处理div.class1.class2格式
                if element.tag_name.lower() == "div":
                    classes = css_selector[4:].split(".")  # 去掉"div."前缀
                    element_classes = element.get_attribute("class") or ""
                    element_class_list = element_classes.split()

                    # 检查所有required classes是否都存在
                    for required_class in classes:
                        if required_class and required_class not in element_class_list:
                            return False
                    return True

            return False
        except:
            return False

    def get_size_column_index(self, table_container):
        """识别SKU表格中“尺码”列的索引"""
        try:
            possible_headers = []
            # 优先从父级查找header
            try:
                wrapper = table_container.find_element(By.XPATH,
                    "ancestor::*[contains(@class, 'pro-virtual-table') or contains(@class, 'virtual-table')][1]")
                possible_headers.append(wrapper)
            except Exception:
                pass

            possible_headers.append(table_container)

            for scope in possible_headers:
                try:
                    header = scope.find_element(By.CSS_SELECTOR, ".pro-virtual-table__header")
                    header_cells = header.find_elements(By.CSS_SELECTOR, "div")
                    for idx, cell in enumerate(header_cells):
                        text = (cell.text or "").strip()
                        if not text:
                            continue
                        if any(keyword in text for keyword in ["尺码", "Size", "size"]):
                            return idx
                except Exception:
                    continue
        except Exception:
            pass
        return None

    def get_color_column_index(self, table_container):
        """识别SKU表格中“颜色”列的索引"""
        try:
            scopes = []
            try:
                wrapper = table_container.find_element(By.XPATH,
                    "ancestor::*[contains(@class, 'pro-virtual-table') or contains(@class, 'virtual-table')][1]")
                scopes.append(wrapper)
            except Exception:
                pass

            scopes.append(table_container)

            for scope in scopes:
                try:
                    header = scope.find_element(By.CSS_SELECTOR, ".pro-virtual-table__header")
                    header_cells = header.find_elements(By.CSS_SELECTOR, "div")
                    for idx, cell in enumerate(header_cells):
                        text = (cell.text or "").strip()
                        if text and any(keyword in text for keyword in ["颜色", "Color", "color"]):
                            return idx
                except Exception:
                    continue
        except Exception:
            pass
        return None

    def extract_size_value_from_row(self, row, column_index):
        """从指定列提取尺码文本"""
        if column_index is None:
            return None
        try:
            row_cells = row.find_elements(By.CSS_SELECTOR, "> div")
            if column_index >= len(row_cells):
                return None
            cell = row_cells[column_index]
            # 直接文本
            text = (cell.text or "").strip()
            normalized = self.normalize_size_text(text)
            if normalized:
                return normalized

            # 尝试读取输入框值
            inputs = cell.find_elements(By.CSS_SELECTOR, "input, textarea")
            for input_elem in inputs:
                value = (input_elem.get_attribute("value") or "").strip()
                normalized = self.normalize_size_text(value)
                if normalized:
                    return normalized

            # 尝试读取下拉选择的展示文本
            spans = cell.find_elements(By.CSS_SELECTOR, "span, div")
            for elem in spans:
                value = (elem.text or "").strip()
                normalized = self.normalize_size_text(value)
                if normalized:
                    return normalized
        except Exception:
            return None
        return None

    def extract_color_value_from_row(self, row, column_index=None, row_text=None):
        """从行中提取颜色文本"""
        color_text = ""
        try:
            def read_cell_text(cell):
                txt = (cell.text or "").strip()
                if txt:
                    return txt
                spans = cell.find_elements(By.CSS_SELECTOR, "span, div")
                for span in spans:
                    t = (span.text or "").strip()
                    if t:
                        return t
                return ""

            # 尝试直接在行内找到颜色候选（包含颜色关键字）
            if not color_text:
                try:
                    candidates = row.find_elements(By.XPATH, ".//*[contains(@class,'color') or contains(@class,'颜色')]")
                    for c in candidates:
                        if c.is_displayed():
                            t = (c.text or "").strip()
                            if t:
                                color_text = t
                                break
                except Exception:
                    pass

            if column_index is not None:
                # 尝试>div和显式row-cell两种结构
                row_cells = row.find_elements(By.CSS_SELECTOR, "> div")
                if column_index < len(row_cells):
                    color_text = read_cell_text(row_cells[column_index])

                if not color_text:
                    row_cells = row.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row-cell")
                    if column_index < len(row_cells):
                        color_text = read_cell_text(row_cells[column_index])
            # 如果未识别到颜色列，但已识别到尺码列，尝试使用尺码列前一列作为颜色列
            if not color_text and column_index is None:
                try:
                    size_col = getattr(self, "size_column_index", None)
                    if size_col is not None and size_col > 0:
                        color_col = size_col - 1
                        row_cells = row.find_elements(By.CSS_SELECTOR, "> div")
                        if color_col < len(row_cells):
                            color_text = read_cell_text(row_cells[color_col])
                        if not color_text:
                            row_cells = row.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row-cell")
                            if color_col < len(row_cells):
                                color_text = read_cell_text(row_cells[color_col])
                except Exception:
                    pass

            # 再兜底：取左侧固定列里第一个非空文本（颜色通常在固定左侧）
            if not color_text:
                try:
                    fixed_left_cells = row.find_elements(By.CSS_SELECTOR, ".pro-virtual-table__row-cell.is-fixed-left")
                    preferred_indexes = [2, 1, 0]  # 0=选择框，1=预览图，2=颜色，3=尺码（部分表头固定）
                    for idx in preferred_indexes:
                        if idx < len(fixed_left_cells):
                            candidate = read_cell_text(fixed_left_cells[idx])
                            if candidate:
                                color_text = candidate
                                break
                    if not color_text:
                        for cell in fixed_left_cells:
                            candidate = read_cell_text(cell)
                            if candidate:
                                color_text = candidate
                                break
                except Exception:
                    pass

            if not color_text and row_text:
                candidates = getattr(self, "actual_selected_colors", [])
                for candidate in candidates:
                    if candidate and candidate in row_text:
                        color_text = candidate
                        break
            if not color_text and row_text:
                color_text = row_text.split()[0] if row_text.split() else ""
        except Exception:
            pass
        if not color_text and row_text:
            print(f"   ⚠️ 行颜色无法识别，行文本片段: '{row_text[:80]}'")
        return color_text

    def normalize_size_text(self, text):
        if not text:
            return ""
        text = text.strip()
        match = re.search(r"\d+", text)
        if match:
            return match.group(0)
        return text

    def row_matches_size(self, row, size, column_index=None, row_text=None):
        """判断当前行是否对应目标尺码"""
        size_str = str(size).strip()
        column_value = self.extract_size_value_from_row(row, column_index)
        if column_value and column_value == size_str:
            return True

        try:
            if row_text is None:
                row_text = row.text or ""
            normalized_text = row_text.replace("\n", " ").strip()
            pattern = rf"(?<!\d){re.escape(size_str)}(?!\d)"
            if re.search(pattern, normalized_text):
                return True
            # 附加语境匹配
            pattern_context = rf"(尺码|size|SIZE)[^\d]*{re.escape(size_str)}(?!\d)"
            if re.search(pattern_context, normalized_text):
                return True
        except Exception:
            pass

        # 最后兜底：查找value等于size的隐藏输入
        try:
            xpath = f".//input[@value='{size_str}']"
            if row.find_elements(By.XPATH, xpath):
                return True
        except Exception:
            pass
        return False

    def record_size_scroll_position(self, scroll_target, size):
        if scroll_target is None or size is None:
            return
        try:
            scroll_pos = self.driver.execute_script("return arguments[0].scrollTop;", scroll_target)
            if not hasattr(self, "size_row_scroll_positions"):
                self.size_row_scroll_positions = {}
            self.size_row_scroll_positions[size] = scroll_pos
        except Exception:
            pass

    def refresh_row_element(self, table_container, size, current_row, expected_color=None):
        """确保虚拟滚动表格中的行引用有效，必要时匹配颜色"""
        size_column_index = getattr(self, "size_column_index", None)
        color_column_index = getattr(self, "color_column_index", None)
        scroll_target = getattr(self, "sku_scroll_target", None)
        scroll_positions = getattr(self, "size_row_scroll_positions", {})

        def ensure_scroll_position():
            if scroll_target is None or size is None:
                return
            if size in scroll_positions:
                try:
                    self.driver.execute_script("arguments[0].scrollTop = arguments[1];", scroll_target,
                                               scroll_positions[size])
                    time.sleep(0.2)
                except Exception:
                    pass

        if current_row is not None:
            try:
                if self.row_matches_size(current_row, size, size_column_index):
                    # 如果颜色也匹配，直接返回；颜色不匹配再尝试刷新
                    if expected_color:
                        color_text = self.extract_color_value_from_row(current_row, color_column_index)
                        if color_text and expected_color == color_text:
                            return current_row
                    else:
                        return current_row
            except StaleElementReferenceException:
                print(f"   ♻️ 检测到尺码 {size} 行元素失效，尝试重新定位")
            except Exception:
                pass

        if table_container is None or size is None:
            return None

        ensure_scroll_position()

        try:
            size_column_index = getattr(self, "size_column_index", None)
            row_selectors = [
                ".pro-virtual-table__row",
                "[class*='table-row']",
                "[class*='sku-row']",
                "tr"
            ]
            for selector in row_selectors:
                try:
                    rows = table_container.find_elements(By.CSS_SELECTOR, selector)
                except Exception:
                    continue
                for row in rows:
                    try:
                        if not row.is_displayed():
                            continue
                        row_text = row.text.strip()
                        if self.row_matches_size(row, size, size_column_index, row_text):
                            # 校验颜色
                            if expected_color:
                                color_text = self.extract_color_value_from_row(row, color_column_index, row_text)
                                if color_text and expected_color != color_text:
                                    continue
                            self.record_size_scroll_position(scroll_target, size)
                            print(f"   ✅ 已刷新尺码 {size} 的行引用")
                            return row
                    except Exception:
                        continue
        except Exception as e:
            print(f"   ⚠️ 刷新尺码 {size} 行失败: {e}")
        return None

    def scroll_and_collect_additional_rows(self, table_container, existing_rows, search_sizes, size_column_index, color_column_index=None):
        """通过滚动容器收集更多SKU行（用于多颜色同尺码场景）"""
        try:
            scroll_target = self.get_scrollable_sku_container(table_container)
            if not scroll_target:
                print("ℹ️ 未找到可滚动的SKU容器，跳过滚动收集")
                return []

            collected = []
            existing_signatures = set()
            for item in existing_rows:
                size = item[0]
                row = item[1]
                color_text = item[2] if len(item) > 2 else ""
                try:
                    sig = f"{color_text}|{size}|{row.text.strip()[:120]}"
                except Exception:
                    sig = f"{color_text}|{size}|{id(row)}"
                existing_signatures.add(sig)

            # 增加滚动次数以确保多颜色场景下所有行都能被收集
            max_scrolls = 30
            no_new_counter = 0
            scroll_step = 300  # 每次滚动300像素,更温和的滚动
            
            for attempt in range(max_scrolls):
                try:
                    # 持续往下滚动,不要回到顶部
                    current_scroll = self.driver.execute_script("return arguments[0].scrollTop;", scroll_target)
                    max_scroll = self.driver.execute_script("return arguments[0].scrollHeight - arguments[0].clientHeight;", scroll_target)
                    
                    if current_scroll >= max_scroll:
                        # 已经到底部,无法继续滚动
                        print(f"   ℹ️ 已滚动到底部 (尝试 {attempt + 1}/{max_scrolls})")
                        no_new_counter += 1
                        if no_new_counter >= 3:
                            break
                    else:
                        # 增量往下滚动
                        new_scroll = min(current_scroll + scroll_step, max_scroll)
                        self.driver.execute_script("arguments[0].scrollTop = arguments[1];", scroll_target, new_scroll)
                except Exception as e:
                    print(f"   ⚠️ 滚动失败: {e}")
                    break
                    
                # 等待虚拟滚动表格渲染新行
                time.sleep(0.4)

                row_selectors = [
                    ".pro-virtual-table__row",
                    "[class*='table-row']",
                    "[class*='sku-row']",
                    "tr"
                ]

                newly_added = 0
                for selector in row_selectors:
                    try:
                        rows = table_container.find_elements(By.CSS_SELECTOR, selector)
                    except Exception:
                        continue
                    for row in rows:
                        try:
                            if not row.is_displayed():
                                continue
                            row_text = row.text.strip()
                            detected_size = None
                            for size in search_sizes:
                                if self.row_matches_size(row, size, size_column_index, row_text):
                                    detected_size = size
                                    break
                            if not detected_size:
                                detected_size = self.extract_size_value_from_row(row, size_column_index)

                            color_text = self.extract_color_value_from_row(row, color_column_index, row_text)

                            if detected_size and detected_size in self.size_data:
                                sig = f"{color_text}|{detected_size}|{row_text[:120]}"
                                if sig not in existing_signatures:
                                    existing_signatures.add(sig)
                                    collected.append((detected_size, row, color_text))
                                    newly_added += 1
                        except Exception:
                            continue

                if newly_added > 0:
                    # 发现新行,重置计数器
                    no_new_counter = 0
                    print(f"   ✅ 本次滚动新增 {newly_added} 行")

                # 连续多次无新增行才停止
                if no_new_counter >= 5:
                    print(f"   ℹ️ 连续 {no_new_counter} 次无新增行，停止滚动")
                    break

            return collected
        except Exception as e:
            print(f"❌ 滚动收集SKU行失败: {e}")
            return []

    def fill_sku_dimensions_and_weight(self):
        """填写SKU表格中的尺寸(长宽高)和重量数据"""
        try:
            print("📏 开始填写SKU尺寸和重量数据...")

            # 1. 找到SKU表格容器 - 直接查找包含长宽高输入框的容器
            print("🔍 查找包含长宽高输入框的SKU表格容器...")
            try:
                # 直接查找包含长宽高输入框的容器
                length_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input[placeholder='长']")
                width_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input[placeholder='宽']")
                height_inputs = self.driver.find_elements(By.CSS_SELECTOR, "input[placeholder='高']")

                print(f"🔍 找到 {len(length_inputs)} 个长度输入框")
                print(f"🔍 找到 {len(width_inputs)} 个宽度输入框")
                print(f"🔍 找到 {len(height_inputs)} 个高度输入框")

                if not (length_inputs and width_inputs and height_inputs):
                    print("❌ 未找到长宽高输入框")
                    return False

                # 找到包含这些输入框的共同父容器
                table_container = None

                # 从第一个长度输入框开始，向上查找包含所有长宽高输入框的容器
                for level in range(1, 10):  # 最多向上查找10层
                    try:
                        parent = length_inputs[0]
                        for _ in range(level):
                            parent = parent.find_element(By.XPATH, "..")

                        # 检查这个父容器是否包含足够的长宽高输入框
                        parent_length_inputs = parent.find_elements(By.CSS_SELECTOR, "input[placeholder='长']")
                        parent_width_inputs = parent.find_elements(By.CSS_SELECTOR, "input[placeholder='宽']")
                        parent_height_inputs = parent.find_elements(By.CSS_SELECTOR, "input[placeholder='高']")

                        if (len(parent_length_inputs) >= 3 and
                            len(parent_width_inputs) >= 3 and
                            len(parent_height_inputs) >= 3):
                            table_container = parent
                            parent_class = parent.get_attribute("class") or ""
                            print(f"✅ 找到SKU表格容器 (第{level}层父级): class='{parent_class[:50]}...'")
                            print(f"   包含 {len(parent_length_inputs)} 个长度输入框")
                            print(f"   包含 {len(parent_width_inputs)} 个宽度输入框")
                            print(f"   包含 {len(parent_height_inputs)} 个高度输入框")
                            break
                    except:
                        continue

                if not table_container:
                    print("❌ 未找到包含足够长宽高输入框的SKU表格容器")
                    return False

            except Exception as e:
                print(f"❌ 查找SKU表格容器失败: {e}")
                return False

            # 额外解析尺码列索引，后续匹配更精准
            size_column_index = self.get_size_column_index(table_container)
            self.size_column_index = size_column_index
            if size_column_index is not None:
                print(f"✅ 识别到尺码列索引: {size_column_index}")
            else:
                print("⚠️ 未能准确识别尺码列索引，将退回到文本匹配")

            # 识别颜色列索引，便于区分不同颜色的SKU行
            color_column_index = self.get_color_column_index(table_container)
            self.color_column_index = color_column_index
            if color_column_index is not None:
                print(f"✅ 识别到颜色列索引: {color_column_index}")
            else:
                print("⚠️ 未能识别颜色列索引，将通过行文本匹配颜色")

            # 为虚拟滚动表格记录容器及行滚动位置
            self.sku_scroll_target = self.get_scrollable_sku_container(table_container)
            self.size_row_scroll_positions = {}

            # 2. 采用即时查找即时填写策略，避免虚拟滚动导致行元素失效
            print("🔍 开始按尺码顺序查找并填写...")
            
            # 确保从顶部开始
            if self.sku_scroll_target:
                try:
                    self.driver.execute_script("arguments[0].scrollTop = 0;", self.sku_scroll_target)
                    time.sleep(0.3)
                except Exception:
                    pass

            actual_sizes = getattr(self, "actual_selected_sizes", [])
            if actual_sizes:
                search_sizes = list(actual_sizes)
                print(f"   将查找实际已选择的尺码: {search_sizes}")
            else:
                search_sizes = list(self.size_data.keys())
                print("   ⚠️ 未获取到实际选择的尺码，回退到尺码模板中的全部尺码")

            # 3. 逐个尺码查找并立即填写（避免虚拟滚动导致元素失效）
            row_selectors = [
                ".pro-virtual-table__row",
                "[class*='table-row']",
                "[class*='sku-row']",
                "tr"
            ]
            
            success_count = 0
            processed_sizes = []
            failed_sizes = []
            processed_signatures = set()  # 记录已处理的行，避免重复
            
            for size in search_sizes:
                if size not in self.size_data:
                    continue
                    
                size_info = self.size_data[size]
                length = size_info["length"]
                width = size_info["width"]
                height = size_info["height"]
                weight = size_info["weight"]
                
                print(f"📏 查找尺码 {size}...")
                
                # 在当前可见区域查找该尺码的所有行（多颜色场景）
                found_rows = []
                try:
                    for selector in row_selectors:
                        try:
                            rows = table_container.find_elements(By.CSS_SELECTOR, selector)
                            for row in rows:
                                if not row.is_displayed():
                                    continue
                                    
                                row_text = row.text.strip()
                                if self.row_matches_size(row, size, size_column_index, row_text):
                                    color_text = self.extract_color_value_from_row(row, color_column_index, row_text)
                                    signature = f"{color_text}|{size}|{row_text[:80]}"
                                    
                                    if signature not in processed_signatures:
                                        found_rows.append((row, color_text, signature))
                                        
                            if found_rows:
                                break  # 找到就不用尝试其他选择器了
                        except Exception:
                            continue
                            
                except Exception as e:
                    print(f"   ⚠️ 查找尺码 {size} 失败: {e}")
                
                # 填写找到的所有行
                if found_rows:
                    for row, color_text, signature in found_rows:
                        try:
                            print(f"   处理尺码 {size} (颜色: {color_text or '未知'})...")
                            print(f"   数据: 长={length}, 宽={width}, 高={height}, 重量={weight}")
                            
                            # 滚动到该行
                            try:
                                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", row)
                                time.sleep(0.2)
                            except Exception:
                                pass
                            
                            # 立即填写
                            if self.fill_row_dimensions_and_weight(row, length, width, height, weight, table_container, size, expected_color=color_text):
                                success_count += 1
                                processed_signatures.add(signature)
                                processed_sizes.append(f"{color_text}-{size}" if color_text else str(size))
                                print(f"   ✅ 尺码 {size} (颜色: {color_text or '未知'}) 数据填写成功")
                                
                                # 填写完后小幅往下滚动，触发下一个尺码的渲染
                                if self.sku_scroll_target:
                                    try:
                                        current = self.driver.execute_script("return arguments[0].scrollTop;", self.sku_scroll_target)
                                        self.driver.execute_script("arguments[0].scrollTop = arguments[1];", self.sku_scroll_target, current + 100)
                                        time.sleep(0.3)
                                    except Exception:
                                        pass
                            else:
                                failed_sizes.append(size)
                                print(f"   ❌ 尺码 {size} 数据填写失败")
                        except Exception as e:
                            print(f"   ❌ 处理尺码 {size} 失败: {e}")
                            continue
                else:
                    # 未找到该尺码，尝试滚动查找
                    print(f"   ⚠️ 尺码 {size} 不在当前可见区域，尝试滚动查找...")
                    if self.sku_scroll_target:
                        for scroll_attempt in range(5):
                            try:
                                current = self.driver.execute_script("return arguments[0].scrollTop;", self.sku_scroll_target)
                                self.driver.execute_script("arguments[0].scrollTop = arguments[1];", self.sku_scroll_target, current + 200)
                                time.sleep(0.4)
                                
                                # 再次查找
                                for selector in row_selectors:
                                    try:
                                        rows = table_container.find_elements(By.CSS_SELECTOR, selector)
                                        for row in rows:
                                            if not row.is_displayed():
                                                continue
                                            row_text = row.text.strip()
                                            if self.row_matches_size(row, size, size_column_index, row_text):
                                                color_text = self.extract_color_value_from_row(row, color_column_index, row_text)
                                                signature = f"{color_text}|{size}|{row_text[:80]}"
                                                
                                                if signature not in processed_signatures:
                                                    print(f"   ✅ 滚动后找到尺码 {size}")
                                                    print(f"   数据: 长={length}, 宽={width}, 高={height}, 重量={weight}")
                                                    
                                                    try:
                                                        self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", row)
                                                        time.sleep(0.2)
                                                    except Exception:
                                                        pass
                                                    
                                                    if self.fill_row_dimensions_and_weight(row, length, width, height, weight, table_container, size, expected_color=color_text):
                                                        success_count += 1
                                                        processed_signatures.add(signature)
                                                        processed_sizes.append(f"{color_text}-{size}" if color_text else str(size))
                                                        print(f"   ✅ 尺码 {size} 数据填写成功")
                                                        found_rows.append((row, color_text, signature))
                                                    else:
                                                        failed_sizes.append(size)
                                                    break
                                        if found_rows:
                                            break
                                    except Exception:
                                        continue
                                if found_rows:
                                    break
                            except Exception as e:
                                print(f"   ⚠️ 滚动查找失败: {e}")
                                break
                    
                    if not found_rows:
                        failed_sizes.append(size)
                        print(f"   ❌ 尺码 {size} 未找到")

            # 报告填写结果
            print(f"✅ SKU尺寸和重量数据填写完成: 成功 {success_count} 行")
            print(f"   📊 成功填写的尺码: {sorted(set(processed_sizes))}")
            if failed_sizes:
                print(f"   ❌ 填写失败的尺码: {sorted(set(failed_sizes))}")

            return success_count > 0

        except Exception as e:
            print(f"❌ 填写SKU尺寸和重量数据失败: {e}")
            return False

    def scroll_and_find_missing_sku_rows(self, table_container, missing_sizes):
        """滚动查找缺失的SKU行"""
        try:
            missing_sizes = set(missing_sizes)
            size_column_index = getattr(self, "size_column_index", None)
            print(f"   🔍 滚动查找缺失的尺码: {sorted(missing_sizes)}")
            additional_rows = []

            scroll_target = getattr(self, "sku_scroll_target", None)
            if not scroll_target:
                scroll_target = self.get_scrollable_sku_container(table_container)
                self.sku_scroll_target = scroll_target
            if scroll_target:
                try:
                    container_class = scroll_target.get_attribute("class") or ""
                    print(f"   ✅ 使用可滚动容器: class='{container_class[:80]}'")
                except Exception:
                    print("   ✅ 使用可滚动容器")
            else:
                print("   ⚠️ 未找到专属的滚动容器，使用窗口滚动")

            row_selectors = [
                ".pro-virtual-table__row",
                "[class*='table-row']",
                "[class*='sku-row']",
                "tr"
            ]

            def collect_rows():
                found = []
                for selector in row_selectors:
                    try:
                        rows = table_container.find_elements(By.CSS_SELECTOR, selector)
                    except Exception:
                        continue

                    for row in rows:
                        try:
                            if not row.is_displayed():
                                continue
                            row_text = row.text.strip()
                            for size in list(missing_sizes):
                                if self.row_matches_size(row, size, size_column_index, row_text):
                                    found.append((size, row))
                                    missing_sizes.remove(size)
                                    self.record_size_scroll_position(scroll_target, size)
                                    print(f"     ✅ 找到尺码 {size} 的SKU行")
                                    break
                        except Exception:
                            continue
                return found

            # 先在当前视图内再检查一遍
            additional_rows.extend(collect_rows())
            if not missing_sizes:
                return additional_rows

            max_attempts = min(12, max(6, len(missing_sizes)))
            stagnant_scrolls = 0
            no_progress_runs = 0

            for attempt in range(max_attempts):
                print(f"   📜 滚动尝试 {attempt + 1}/{max_attempts}...")

                prev_top = None
                scrolled = False
                if scroll_target:
                    try:
                        prev_top = self.driver.execute_script("return arguments[0].scrollTop;", scroll_target)
                    except Exception:
                        prev_top = None

                    try:
                        self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollTop + 350;", scroll_target)
                        scrolled = True
                    except Exception:
                        scrolled = False

                    time.sleep(0.5)

                    try:
                        new_top = self.driver.execute_script("return arguments[0].scrollTop;", scroll_target)
                    except Exception:
                        new_top = None

                    if prev_top is not None and new_top is not None and new_top == prev_top:
                        scrolled = False
                else:
                    new_top = None

                if not scrolled:
                    print("     ℹ️ 容器滚动无变化，改用window滚动")
                    self.driver.execute_script("window.scrollBy(0, 400);")
                    time.sleep(0.5)
                    prev_top = None
                    new_top = None

                new_rows = collect_rows()
                if new_rows:
                    additional_rows.extend(new_rows)
                found_this_round = bool(new_rows)
                if not missing_sizes:
                    break

                if prev_top is not None and new_top is not None and new_top == prev_top:
                    stagnant_scrolls += 1
                    if stagnant_scrolls >= 2:
                        print("   ⚠️ 滚动位置未变化，可能已到达底部")
                        break
                else:
                    stagnant_scrolls = 0

                if not found_this_round:
                    no_progress_runs += 1
                    if no_progress_runs >= 3:
                        print("   ⚠️ 连续多次滚动未找到新尺码，提前结束")
                        break
                else:
                    no_progress_runs = 0

            if missing_sizes:
                print(f"   ⚠️ 滚动后仍未找到的尺码: {sorted(missing_sizes)}")

            return additional_rows

        except Exception as e:
            print(f"   ❌ 滚动查找失败: {e}")
            return []

    def get_scrollable_sku_container(self, table_container):
        """尝试找到SKU表格可滚动的容器"""
        try:
            # 优先检查自身及其祖先
            current = table_container
            for level in range(6):
                if self.is_scrollable_element(current):
                    return current
                try:
                    current = current.find_element(By.XPATH, "..")
                except Exception:
                    break

            # 再检查典型容器
            selectors = [
                ".pro-virtual-table__body",
                ".pro-virtual-table__viewport",
                ".pro-virtual-table__content",
                "[class*='virtual-table__body']",
                "[class*='table__body']",
                ".sku-table-container",
                ".sku-table-body",
            ]

            for scope in (table_container, self.driver):
                for selector in selectors:
                    try:
                        elements = scope.find_elements(By.CSS_SELECTOR, selector)
                    except Exception:
                        continue
                    for element in elements:
                        if element.is_displayed() and self.is_scrollable_element(element):
                            return element

            return None
        except Exception:
            return None

    def is_scrollable_element(self, element):
        """判断元素是否可滚动"""
        try:
            scroll_height = self.driver.execute_script("return arguments[0].scrollHeight || 0;", element)
            client_height = self.driver.execute_script("return arguments[0].clientHeight || 0;", element)
            overflow_y = self.driver.execute_script(
                "return window.getComputedStyle(arguments[0]).overflowY || '';", element)
            if scroll_height - client_height > 5:
                return True
            return overflow_y in ("auto", "scroll")
        except Exception:
            return False

    def fill_row_dimensions_and_weight(self, row, length, width, height, weight, table_container=None, size=None, expected_color=None):
        """填写单行的尺寸和重量数据"""
        try:
            row = self.refresh_row_element(table_container, size, row, expected_color=expected_color)
            if not row:
                print(f"   ❌ 尺码 {size} 行已失效，无法填写")
                return False

            try:
                self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", row)
                time.sleep(0.2)
            except Exception:
                pass

            print(f"   🔍 分析行结构...")

            dimension_inputs = None
            for attempt in range(3):
                try:
                    # 方法1：通过列标题定位输入框
                    dimension_inputs = self.find_dimension_inputs_by_headers(row)

                    if not dimension_inputs:
                        # 方法2：通过输入框的位置和属性定位
                        dimension_inputs = self.find_dimension_inputs_by_position(row)

                    if dimension_inputs:
                        break
                except StaleElementReferenceException:
                    print(f"   ♻️ 尺码 {size} 行结构发生变化，重新定位 (尝试 {attempt + 1})")
                    row = self.refresh_row_element(table_container, size, row)
                    if not row:
                        break
                    time.sleep(0.2)
                    continue

            if not dimension_inputs:
                print(f"   ❌ 无法找到尺寸和重量输入框")
                return False

            # 如果本行已填写过(长/宽/高/重都有值)，则跳过，避免重复覆盖
            try:
                pre_values = {k: (v.get_attribute("value") or "").strip() for k, v in dimension_inputs.items()}
                if all(pre_values.get(key) for key in ("length", "width", "height", "weight")):
                    print("   ℹ️ 本行长宽高重量已存在，跳过填写以避免重复覆盖")
                    return True
            except Exception:
                pass

            # 填写数据并验证
            success_count = 0
            data_map = {
                "length": {"value": length, "label": "长"},
                "width": {"value": width, "label": "宽"},
                "height": {"value": height, "label": "高"},
                "weight": {"value": weight, "label": "重量"}
            }

            print(f"   📝 开始填写数据...")
            for field_type, input_elem in dimension_inputs.items():
                if field_type in data_map:
                    try:
                        data = data_map[field_type]
                        value = data["value"]
                        label = data["label"]

                        # 获取填写前的值
                        old_value = input_elem.get_attribute("value") or ""

                        # 清空并填写数据
                        input_elem.clear()
                        time.sleep(0.1)
                        input_elem.send_keys(str(value))
                        time.sleep(0.2)

                        # 验证填写结果
                        new_value = input_elem.get_attribute("value") or ""

                        if str(value) in new_value:
                            print(f"     ✅ {label}: {value} (验证成功: '{new_value}')")
                            success_count += 1
                        else:
                            print(f"     ❌ {label}: {value} (验证失败: 期望'{value}', 实际'{new_value}')")

                    except Exception as e:
                        print(f"     ❌ 填写{data['label']}失败: {e}")
                        continue

            return success_count >= 3  # 至少成功填写3个字段

        except Exception as e:
            print(f"   ❌ 填写行数据失败: {e}")
            return False

    def find_dimension_inputs_by_headers(self, row):
        """通过列标题定位尺寸和重量输入框"""
        try:
            dimension_inputs = {}

            # 查找行中的所有输入框
            input_elements = row.find_elements(By.CSS_SELECTOR, "input[type='text'], input:not([type])")

            print(f"   🔍 找到 {len(input_elements)} 个文本输入框")

            # 首先尝试通过表格头部定位
            try:
                # 查找表格头部
                table_body = row.find_element(By.XPATH, "ancestor::*[contains(@class, 'pro-virtual-table__body')]")
                table_header = table_body.find_element(By.CSS_SELECTOR, ".pro-virtual-table__header")
                header_cells = table_header.find_elements(By.CSS_SELECTOR, "div")

                print(f"   🔍 分析表格头部，找到 {len(header_cells)} 个头部单元格")

                # 分析头部单元格，找到尺寸相关的列
                dimension_columns = {}
                for i, header_cell in enumerate(header_cells):
                    try:
                        header_text = header_cell.text.strip()
                        # 清理换行符和多余空格，避免CSS选择器错误
                        header_text = ' '.join(header_text.split())
                        if header_text:
                            print(f"     头部{i+1}: '{header_text}'")

                            if "长" in header_text and "CM" in header_text:
                                dimension_columns["length"] = i
                                print(f"       -> 识别为长度列")
                            elif "宽" in header_text and "CM" in header_text:
                                dimension_columns["width"] = i
                                print(f"       -> 识别为宽度列")
                            elif "高" in header_text and "CM" in header_text:
                                dimension_columns["height"] = i
                                print(f"       -> 识别为高度列")
                            elif "重量" in header_text and "G" in header_text:
                                dimension_columns["weight"] = i
                                print(f"       -> 识别为重量列")
                            elif "尺寸" in header_text and "CM" in header_text:
                                # 尺寸列可能包含长宽高的子输入框
                                dimension_columns["dimensions"] = i
                                print(f"       -> 识别为尺寸列（可能包含长宽高）")
                    except:
                        continue

                # 根据列索引找到对应的输入框
                if dimension_columns:
                    row_cells = row.find_elements(By.CSS_SELECTOR, "> div")
                    print(f"   🔍 当前行有 {len(row_cells)} 个单元格")

                    for field_type, col_index in dimension_columns.items():
                        if col_index < len(row_cells):
                            try:
                                cell = row_cells[col_index]
                                cell_inputs = cell.find_elements(By.CSS_SELECTOR, "input")

                                if field_type == "dimensions" and len(cell_inputs) >= 3:
                                    # 尺寸列包含长宽高三个输入框
                                    dimension_inputs["length"] = cell_inputs[0]
                                    dimension_inputs["width"] = cell_inputs[1]
                                    dimension_inputs["height"] = cell_inputs[2]
                                    print(f"     ✅ 通过头部定位在尺寸列找到长宽高输入框 (列{col_index+1})")
                                elif field_type != "dimensions" and cell_inputs:
                                    dimension_inputs[field_type] = cell_inputs[0]
                                    field_name = {"length": "长度", "width": "宽度", "height": "高度", "weight": "重量"}[field_type]
                                    print(f"     ✅ 通过头部定位找到{field_name}输入框 (列{col_index+1})")
                            except:
                                continue

            except Exception as e:
                print(f"   ⚠️ 通过表格头部定位失败: {e}")
                # 如果是无效选择器错误，直接跳过头部定位
                if "invalid selector" in str(e).lower():
                    print(f"   ⚠️ 检测到无效选择器错误，跳过头部定位方法")

            # 如果头部定位失败，尝试通过上下文定位
            if not dimension_inputs:
                print(f"   🔍 尝试通过上下文定位...")

                # 分析每个输入框的上下文，确定其用途
                for i, input_elem in enumerate(input_elements):
                    try:
                        if not (input_elem.is_displayed() and input_elem.is_enabled()):
                            continue

                        # 获取输入框的属性
                        placeholder = input_elem.get_attribute("placeholder") or ""

                        # 查找输入框所在的列或单元格
                        parent_cell = input_elem
                        for level in range(5):  # 向上查找5层
                            parent_cell = parent_cell.find_element(By.XPATH, "..")
                            cell_text = parent_cell.text.strip()

                            # 根据单元格内容判断字段类型
                            if "长" in cell_text and "CM" in cell_text and "length" not in dimension_inputs:
                                dimension_inputs["length"] = input_elem
                                print(f"     📏 通过上下文找到长度输入框 (位置{i+1}): '{cell_text[:20]}...'")
                                break
                            elif "宽" in cell_text and "CM" in cell_text and "width" not in dimension_inputs:
                                dimension_inputs["width"] = input_elem
                                print(f"     📏 通过上下文找到宽度输入框 (位置{i+1}): '{cell_text[:20]}...'")
                                break
                            elif "高" in cell_text and "CM" in cell_text and "height" not in dimension_inputs:
                                dimension_inputs["height"] = input_elem
                                print(f"     📏 通过上下文找到高度输入框 (位置{i+1}): '{cell_text[:20]}...'")
                                break
                            elif "重量" in cell_text and "G" in cell_text and "weight" not in dimension_inputs:
                                dimension_inputs["weight"] = input_elem
                                print(f"     ⚖️ 通过上下文找到重量输入框 (位置{i+1}): '{cell_text[:20]}...'")
                                break

                    except Exception as e:
                        continue

            if len(dimension_inputs) >= 3:
                print(f"   ✅ 通过标题定位找到 {len(dimension_inputs)} 个字段")
                return dimension_inputs
            else:
                print(f"   ⚠️ 通过标题定位只找到 {len(dimension_inputs)} 个字段")
                return None

        except Exception as e:
            print(f"   ❌ 通过标题定位输入框失败: {e}")
            return None

    def find_dimension_inputs_by_position(self, row):
        """通过位置定位尺寸和重量输入框 - 改进版"""
        try:
            dimension_inputs = {}

            # 查找行中的所有输入框
            input_elements = row.find_elements(By.CSS_SELECTOR, "input[type='text'], input:not([type])")

            print(f"   🔍 找到 {len(input_elements)} 个输入框，开始详细分析...")

            # 分析每个输入框的位置和属性
            valid_inputs = []
            for i, input_elem in enumerate(input_elements):
                try:
                    if input_elem.is_displayed() and input_elem.is_enabled():
                        placeholder = input_elem.get_attribute("placeholder") or ""
                        class_name = input_elem.get_attribute("class") or ""
                        value = input_elem.get_attribute("value") or ""

                        # 获取输入框的父元素信息
                        try:
                            parent = input_elem.find_element(By.XPATH, "..")
                            parent_text = parent.text.strip()[:20]  # 只取前20个字符
                        except:
                            parent_text = ""

                        print(f"     输入框{i+1}: placeholder='{placeholder}', parent_text='{parent_text}', value='{value}'")

                        # 排除明显不是尺寸的输入框
                        exclude_keywords = ["color", "image", "pic", "颜色", "图片", "预览", "编码", "SKU", "价格"]
                        is_excluded = any(keyword in placeholder.lower() + class_name.lower() + parent_text.lower()
                                        for keyword in exclude_keywords)

                        if not is_excluded:
                            valid_inputs.append((i, input_elem))
                            print(f"       -> 标记为有效输入框")
                        else:
                            print(f"       -> 排除（包含排除关键词）")
                except:
                    continue

            print(f"   🔍 筛选出 {len(valid_inputs)} 个有效输入框")

            # 优先查找有明确placeholder的尺寸输入框
            if len(valid_inputs) >= 4:
                # 首先尝试通过placeholder精确匹配
                dimension_inputs_by_placeholder = {}

                for i, (original_index, input_elem) in enumerate(valid_inputs):
                    try:
                        placeholder = input_elem.get_attribute("placeholder") or ""
                        if placeholder == "长":
                            dimension_inputs_by_placeholder["length"] = input_elem
                            print(f"     ✅ 通过placeholder找到长输入框 -> 原始位置{original_index + 1}")
                        elif placeholder == "宽":
                            dimension_inputs_by_placeholder["width"] = input_elem
                            print(f"     ✅ 通过placeholder找到宽输入框 -> 原始位置{original_index + 1}")
                        elif placeholder == "高":
                            dimension_inputs_by_placeholder["height"] = input_elem
                            print(f"     ✅ 通过placeholder找到高输入框 -> 原始位置{original_index + 1}")
                    except:
                        continue

                # 如果通过placeholder找到了长宽高，查找重量输入框（通常在高输入框后面）
                if len(dimension_inputs_by_placeholder) >= 3:
                    # 找到高输入框的位置，重量输入框通常在其后面
                    height_found = False
                    for i, (original_index, input_elem) in enumerate(valid_inputs):
                        if height_found:
                            # 高输入框后面的第一个输入框通常是重量
                            dimension_inputs_by_placeholder["weight"] = input_elem
                            print(f"     ✅ 推测重量输入框 -> 原始位置{original_index + 1}")
                            break

                        if input_elem == dimension_inputs_by_placeholder.get("height"):
                            height_found = True

                if len(dimension_inputs_by_placeholder) == 4:
                    dimension_inputs = dimension_inputs_by_placeholder
                    print(f"   ✅ 通过placeholder精确匹配找到所有4个字段")
                else:
                    print(f"   ⚠️ placeholder匹配只找到 {len(dimension_inputs_by_placeholder)} 个字段，尝试位置推测")

                    # 如果placeholder匹配不完整，回退到位置推测
                    # 根据调试信息，长宽高重量输入框通常在后面的位置
                    if len(valid_inputs) >= 4:
                        # 尝试从后面开始的4个输入框
                        start_idx = max(0, len(valid_inputs) - 4)
                        selected_inputs = valid_inputs[start_idx:start_idx + 4]

                        print(f"   🧪 尝试从位置{start_idx + 1}开始的4个输入框:")

                        dimension_fields = ["length", "width", "height", "weight"]
                        labels = ["长", "宽", "高", "重量"]
                        temp_inputs = {}

                        for i, (field, label) in enumerate(zip(dimension_fields, labels)):
                            if i < len(selected_inputs):
                                original_index, input_elem = selected_inputs[i]
                                temp_inputs[field] = input_elem
                                print(f"     📏 {label}输入框 -> 原始位置{original_index + 1}")

                        if len(temp_inputs) == 4:
                            dimension_inputs = temp_inputs
                            print(f"   ✅ 选择从位置{start_idx + 1}开始的输入框组")

                if dimension_inputs:
                    return dimension_inputs
                else:
                    print(f"   ⚠️ 未找到合适的4个连续输入框")
                    return None
            else:
                print(f"   ⚠️ 有效输入框数量不足: {len(valid_inputs)}")
                return None

        except Exception as e:
            print(f"   ❌ 通过位置定位输入框失败: {e}")
            return None

def test_sku_category_batch_modify_only():
    """专门测试SKU分类批量修改功能"""
    try:
        print("🧪 开始测试SKU分类批量修改功能")
        print("=" * 60)

        # 创建ERP自动化实例
        erp = ERPAutomation(category_option=SELECTED_CATEGORY_OPTION)

        # 加载产品数据
        print("1️⃣ 加载产品数据...")
        if not erp.load_product_data():
            print("❌ 无法读取产品数据")
            return

        # 设置浏览器
        print("2️⃣ 设置浏览器...")
        if not erp.setup_browser():
            print("❌ 浏览器设置失败")
            return

        # 登录ERP系统
        print("3️⃣ 登录ERP系统...")
        if not erp.login_erp():
            print("❌ ERP登录失败")
            return

        # 处理登录后的弹窗
        print("4️⃣ 处理登录后弹窗...")
        erp.handle_popups()
        time.sleep(3)

        # 快速等待页面加载
        print("5️⃣ 快速等待页面加载...")
        time.sleep(2)

        # 直接测试SKU分类批量修改功能
        print("6️⃣ 开始测试SKU分类批量修改功能...")
        print("   🎯 预期操作: 找到SKU分类批量按钮 -> 点击 -> 选择单品 -> 确认修改")
        print("-" * 40)

        result = erp.batch_modify_sku_category()

        print("-" * 40)
        if result:
            print("✅ SKU分类批量修改功能测试成功")
        else:
            print("❌ SKU分类批量修改功能测试失败")

        print("\n🔍 测试完成，浏览器保持打开状态供检查")
        print("📝 请查看上方的详细执行日志")

        # 保持浏览器打开，不自动关闭
        input("\n按回车键关闭浏览器...")

    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")
        import traceback
        traceback.print_exc()

    finally:
        # 关闭浏览器
        if 'erp' in locals() and erp.driver:
            erp.driver.quit()
            print("🔚 浏览器已关闭")

def test_preview_image_menu_only():
    """专门测试预览图批量菜单内容"""
    try:
        print("🧪 开始测试预览图批量菜单内容")
        print("=" * 60)

        # 创建ERP自动化实例
        erp = ERPAutomation(category_option=SELECTED_CATEGORY_OPTION)

        # 加载产品数据
        print("1️⃣ 加载产品数据...")
        if not erp.load_product_data():
            print("❌ 无法读取产品数据")
            return

        # 设置浏览器
        print("2️⃣ 设置浏览器...")
        if not erp.setup_browser():
            print("❌ 浏览器设置失败")
            return

        # 登录ERP系统
        print("3️⃣ 登录ERP系统...")
        if not erp.login_erp():
            print("❌ ERP登录失败")
            return

        # 处理登录后的弹窗
        print("4️⃣ 处理登录后弹窗...")
        erp.handle_popups()
        time.sleep(3)

        # 点击创建产品按钮
        print("5️⃣ 打开创建产品弹窗...")
        if not erp.click_create_product():
            print("❌ 创建产品弹窗打开失败")
            return

        # 等待页面加载
        print("6️⃣ 等待页面完全加载...")
        time.sleep(8)

        # 模拟产品创建流程到SKU表格
        print("7️⃣ 模拟产品创建流程...")

        # 获取第一个产品数据用于测试
        if erp.product_data and erp.product_data.products:
            test_product = erp.product_data.products[0]
            print(f"   使用测试产品: {test_product['产品标题']}")

            # 填充产品类别
            print("   📝 填充产品类别...")
            category = test_product.get('产品类别', erp.default_category_path)
            if erp.fill_product_category(category):
                print("   ✅ 产品类别填充成功")
                time.sleep(5)  # 等待属性字段加载

                # 填充产品信息
                print("   📝 填充产品信息...")
                erp.fill_product_info(test_product)
                time.sleep(3)

                # 处理SKU属性（包括颜色和尺码选择）
                print("   📝 处理SKU属性...")
                if erp.handle_sku_attributes(test_product):
                    print("   ✅ SKU属性处理成功")

                    # 现在专门测试预览图批量菜单
                    print("\n8️⃣ 开始测试预览图批量菜单...")
                    print("-" * 40)

                    # 滚动到页面底部，确保SKU表格可见
                    print("📜 滚动到页面底部，确保SKU表格可见...")
                    erp.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                    time.sleep(2)

                    # 按照指定路径找到表格头部容器
                    try:
                        sku_property_list = erp.driver.find_element(By.CSS_SELECTOR, ".sku-property-list")
                        parent = sku_property_list.find_element(By.XPATH, "..")
                        sibling_divs = parent.find_elements(By.XPATH, "./div")
                        last_sibling_div = sibling_divs[-1]
                        last_div_children = last_sibling_div.find_elements(By.XPATH, "./div")
                        second_div = last_div_children[1]
                        second_div_children = second_div.find_elements(By.XPATH, "./div")
                        third_div = second_div_children[2]
                        third_div_children = third_div.find_elements(By.XPATH, "./div")
                        first_div_level4 = third_div_children[0]
                        level4_children = first_div_level4.find_elements(By.XPATH, "./div")
                        first_div_level5 = level4_children[0]
                        level5_children = first_div_level5.find_elements(By.XPATH, "./div")
                        table_header = level5_children[0]

                        print("✅ 找到表格头部容器")

                        # 找到第二个div（预览图列）
                        header_divs = table_header.find_elements(By.XPATH, "./div")
                        second_div = header_divs[1]  # 第二个div
                        print(f"   第二个div文本: '{second_div.text.strip()}'")

                        # 找到并点击批量按钮
                        button = second_div.find_element(By.TAG_NAME, "button")
                        print(f"   批量按钮文本: '{button.text.strip()}'")

                        erp.driver.execute_script("arguments[0].click();", button)
                        print("✅ 成功点击预览图批量按钮")
                        time.sleep(2)

                        # 查找下拉菜单
                        dropdown_menu = erp.driver.find_element(By.CSS_SELECTOR, ".jx-dropdown-menu.jx-dropdown-menu--small")
                        li_elements = dropdown_menu.find_elements(By.TAG_NAME, "li")

                        print(f"\n🔍 预览图批量下拉菜单包含 {len(li_elements)} 个选项:")
                        for i, li in enumerate(li_elements):
                            li_text = li.text.strip()
                            print(f"   选项{i+1}: '{li_text}'")

                        print("\n📝 结论:")
                        if any("一件填充" in li.text for li in li_elements):
                            print("   ✅ 找到'一件填充'选项")
                        else:
                            print("   ❌ 未找到'一件填充'选项")
                            print("   💡 建议：检查是否需要其他条件才能显示'一件填充'选项")
                            print("   💡 或者'一件填充'功能可能在其他位置")

                    except Exception as e:
                        print(f"❌ 测试预览图批量菜单失败: {e}")

                else:
                    print("   ❌ SKU属性处理失败")
            else:
                print("   ❌ 产品类别填充失败")
        else:
            print("❌ 没有产品数据可用于测试")

        print("\n🔍 测试完成，浏览器保持打开状态供检查")
        input("\n按回车键关闭浏览器...")

    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")
        import traceback
        traceback.print_exc()

    finally:
        # 关闭浏览器
        if 'erp' in locals() and erp.driver:
            erp.driver.quit()
            print("🔚 浏览器已关闭")

def test_size_chart_only():
    """专门测试尺码表选择功能 - 完整流程版本"""
    try:
        print("🧪 开始测试尺码表选择功能（完整流程）")
        print("=" * 60)

        # 创建ERP自动化实例
        erp = ERPAutomation(category_option=SELECTED_CATEGORY_OPTION)

        # 加载产品数据
        print("1️⃣ 加载产品数据...")
        if not erp.load_product_data():
            print("❌ 无法读取产品数据")
            return

        # 设置浏览器
        print("2️⃣ 设置浏览器...")
        if not erp.setup_browser():
            print("❌ 浏览器设置失败")
            return

        # 登录ERP系统
        print("3️⃣ 登录ERP系统...")
        if not erp.login_erp():
            print("❌ ERP登录失败")
            return

        # 处理登录后的弹窗
        print("4️⃣ 处理登录后弹窗...")
        erp.handle_popups()
        time.sleep(3)

        # 点击创建产品按钮
        print("5️⃣ 打开创建产品弹窗...")
        if not erp.click_create_product():
            print("❌ 创建产品弹窗打开失败")
            return

        # 快速等待页面加载
        print("6️⃣ 快速等待页面加载...")
        time.sleep(3)

        # 测试主货号字段填写和外包装图片上传
        print("7️⃣ 测试主货号字段填写和外包装图片上传...")

        # 获取第一个产品数据用于测试
        if erp.product_data and erp.product_data.products:
            test_product = erp.product_data.products[0]
            print(f"   使用测试产品: {test_product['产品标题']}")

            # 注释掉前面的填写步骤
            print("   ⏭️ 跳过产品类别填充...")

            # 测试主货号字段填写
            print("   📝 测试主货号字段填写...")
            erp.fill_main_product_code(test_product.get('主货号', ''))
            time.sleep(2)

            print("   ⏭️ 跳过其他产品信息填充...")

            # 测试轮播图上传功能（包含图片重命名和搜索选择）
            print("   📸 测试轮播图上传功能...")
            erp.upload_product_images(test_product)
            time.sleep(3)

            print("   ⏭️ 跳过SKU属性处理...")
            print("   ⏭️ 跳过包装字段选择...")

            # 等待页面加载
            print("   ⏳ 等待页面元素加载...")
            time.sleep(3)

            # 直接调试外包装图片上传功能
            print("\n8️⃣ 开始调试外包装图片上传功能...")
            print("   🎯 目标: 找到并点击'选择空间图片'按钮")
            print("-" * 40)

            # 调用外包装图片上传调试函数
            result = erp.debug_package_image_upload()

            print("-" * 40)
            if result:
                print("✅ 外包装图片上传调试成功")
            else:
                print("❌ 外包装图片上传调试失败")
        else:
            print("❌ 没有产品数据可用于测试")

        print("\n🔍 测试完成，浏览器保持打开状态供检查")
        print("📝 请查看上方的详细执行日志")

        # 保持浏览器打开，不自动关闭
        input("\n按回车键关闭浏览器...")

    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")
        import traceback
        traceback.print_exc()

    finally:
        # 关闭浏览器
        if 'erp' in locals() and erp.driver:
            erp.driver.quit()
            print("🔚 浏览器已关闭")

def main(daily_limit=200):
    """主函数 - 处理所有工作表的产品"""
    print(f"🚀 开始ERP自动化流程 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("📊 将处理所有工作表的产品数据")

    # 创建自动化实例（不指定类别路径）
    erp = ERPAutomation(daily_limit)
    
    try:
        # 第一步：读取Excel文件的所有工作表
        print("\n=== 第一步：读取所有产品数据 ===")
        if not erp.load_product_data():
            print("❌ 无法读取产品数据，程序退出")
            return
        
        # 第二步：设置浏览器并登录
        print("\n=== 第二步：登录ERP系统 ===")
        if not erp.setup_browser():
            print("❌ 浏览器设置失败，程序退出")
            return
        
        if not erp.login_erp():
            print("❌ 登录失败，程序退出")
            return

        # 第三步：处理登录后的弹窗
        print("\n=== 第三步：处理登录后弹窗 ===")
        erp.handle_popups()

        # 第四步：循环处理每个工作表的产品
        print("\n=== 第四步：批量创建产品 ===")
        
        if not erp.product_data.products_by_sheet:
            print("❌ 没有找到任何产品数据")
            return
        
        # 遍历所有工作表
        for sheet_name, products in erp.product_data.products_by_sheet.items():
            print(f"\n📄 开始处理工作表: {sheet_name}")
            print(f"   包含 {len(products)} 个产品")
            
            # 从 CATEGORY_SHEET_MAPPING 中获取对应的类别路径
            category_path = None
            for config in CATEGORY_SHEET_MAPPING.values():
                if config['sheet_name'] == sheet_name:
                    category_path = config['category_path']
                    break
            
            if not category_path:
                print(f"   ⚠️ 警告：未找到工作表 '{sheet_name}' 对应的类别路径，跳过")
                continue
            
            print(f"   ✅ 使用类别路径: {category_path}")
            
            # 设置当前类别路径
            erp.current_category_path = category_path
            
            # 临时设置产品列表（为了兼容 batch_create_products 方法）
            erp.product_data.products = products
            
            # 批量创建该工作表的产品
            erp.batch_create_products()
            
            print(f"\n✅ 工作表 '{sheet_name}' 处理完成")

        print("\n✅ 所有工作表处理完成")

    except Exception as e:
        print(f"❌ 程序执行出错: {e}")
        import traceback
        traceback.print_exc()

    finally:
        try:
            erp.close_browser()
        except:
            pass
        print("✅ 程序执行完成")

def process_single_product(product_data, process_id, shared_config, startup_delay=0):
    """
    处理单个产品的工作进程函数

    Args:
        product_data: 单个产品的数据字典
        process_id: 进程ID (1, 2, 3...)
        shared_config: 共享配置信息
        startup_delay: 启动延迟时间（秒）
    """
    # 添加启动延迟，避免并发冲突
    if startup_delay > 0:
        print(f"⏳ 进程 {process_id} 等待 {startup_delay} 秒后启动...")
        time.sleep(startup_delay)

    print(f"🚀 进程 {process_id} 开始处理产品: {product_data.get('产品标题:', '')[:30]}...")

    try:
        # 创建每日限制管理器，检查是否还能创建
        daily_limit = shared_config.get('daily_limit', 200)
        limit_manager = DailyLimitManager(daily_limit)

        # 检查每日限制
        if not limit_manager.can_create_more():
            print(f"🚫 进程 {process_id} 检测到今日创建配额已用完，停止处理")
            limit_manager.print_daily_summary()
            return False

        remaining = limit_manager.get_remaining_quota()
        print(f"📊 进程 {process_id} 当前剩余配额: {remaining}")

        # 从产品数据中获取类别路径
        category_path = product_data.get('_category_path')
        
        # 创建独立的ERP自动化实例
        erp = ERPAutomation(daily_limit, category_path=category_path)

        # 设置进程特定的配置
        erp.process_id = process_id
        erp.shared_image_dir = shared_config.get('image_dir', './ready/')
        
        print(f"📋 进程 {process_id} 使用类别路径: {category_path}")

        # 初始化浏览器
        if not erp.setup_browser():
            print(f"❌ 进程 {process_id} 浏览器初始化失败")
            return False

        # 登录ERP系统
        if not erp.login_erp():
            print(f"❌ 进程 {process_id} 登录失败")
            erp.close_browser()
            return False

        print(f"✅ 进程 {process_id} 登录成功")

        # 处理单个产品
        success = erp.process_single_product_data(product_data)

        if success:
            print(f"✅ 进程 {process_id} 产品处理成功: {product_data.get('产品标题:', '')[:30]}")
            # 记录成功创建
            if not erp.daily_limit_manager.record_success():
                print(f"🚫 进程 {process_id} 达到每日创建限制，后续进程将停止")
        else:
            print(f"❌ 进程 {process_id} 产品处理失败: {product_data.get('产品标题:', '')[:30]}")
            # 记录失败
            erp.daily_limit_manager.record_failure()

        # 关闭浏览器
        erp.close_browser()
        return success

    except Exception as e:
        print(f"❌ 进程 {process_id} 处理产品时出错: {e}")
        try:
            if 'erp' in locals():
                erp.close_browser()
        except:
            pass
        return False

def process_multiple_products_erp(products_batch, process_id, shared_config, startup_delay=0):
    """
    处理多个产品的工作进程函数（保持浏览器打开）

    Args:
        products_batch: 产品数据列表
        process_id: 进程ID (1, 2, 3...)
        shared_config: 共享配置信息
        startup_delay: 启动延迟时间（秒）
    """
    # 添加启动延迟，避免并发冲突
    if startup_delay > 0:
        print(f"⏳ 进程 {process_id} 等待 {startup_delay} 秒后启动...")
        time.sleep(startup_delay)

    print(f"🚀 进程 {process_id} 开始处理 {len(products_batch)} 个产品...")

    erp = None
    success_count = 0
    failed_count = 0

    try:
        # 创建每日限制管理器
        daily_limit = shared_config.get('daily_limit', 200)
        limit_manager = DailyLimitManager(daily_limit)

        # 检查每日限制
        if not limit_manager.can_create_more():
            print(f"🚫 进程 {process_id} 检测到今日创建配额已用完，停止处理")
            limit_manager.print_daily_summary()
            return {"success_count": 0, "failed_count": 0, "process_id": process_id, "stopped_by_limit": True}

        remaining = limit_manager.get_remaining_quota()
        print(f"📊 进程 {process_id} 当前剩余配额: {remaining}")

        # 从第一个产品中获取类别路径（批次中所有产品应该有相同的类别路径）
        category_path = products_batch[0].get('_category_path') if products_batch else None
        
        # 创建独立的ERP自动化实例
        erp = ERPAutomation(daily_limit, category_path=category_path)

        # 设置进程特定的配置
        erp.process_id = process_id
        erp.shared_image_dir = shared_config.get('image_dir', './ready/')
        
        if category_path:
            print(f"📋 进程 {process_id} 使用类别路径: {category_path}")

        # 初始化浏览器
        if not erp.setup_browser():
            print(f"❌ 进程 {process_id} 浏览器初始化失败")
            return {"success_count": 0, "failed_count": len(products_batch), "process_id": process_id}

        # 登录ERP系统
        if not erp.login_erp():
            print(f"❌ 进程 {process_id} 登录失败")
            erp.close_browser()
            return {"success_count": 0, "failed_count": len(products_batch), "process_id": process_id}

        print(f"✅ 进程 {process_id} 登录成功，开始处理产品...")

        # 循环处理每个产品，保持浏览器打开
        for i, product_data in enumerate(products_batch, 1):
            try:
                # 在处理每个产品前检查每日限制
                if not erp.daily_limit_manager.can_create_more():
                    print(f"🚫 进程 {process_id} 在处理第 {i} 个产品时达到每日限制，停止处理")
                    erp.daily_limit_manager.print_daily_summary()
                    break

                print(f"📦 进程 {process_id} 处理第 {i}/{len(products_batch)} 个产品: {product_data.get('产品标题:', '')[:30]}...")

                # 处理单个产品（不关闭浏览器）
                success = erp.process_single_product_data(product_data)

                if success:
                    success_count += 1
                    print(f"✅ 进程 {process_id} 产品 {i} 处理成功")

                    # 记录成功创建
                    if not erp.daily_limit_manager.record_success():
                        print(f"🚫 进程 {process_id} 达到每日创建限制，停止处理剩余产品")
                        break

                    # 产品保存成功后，等待弹窗自动关闭，然后寻找创建产品按钮
                    print(f"⏳ 进程 {process_id} 等待弹窗关闭...")
                    time.sleep(3)  # 等待弹窗自动关闭

                    # 如果还有下一个产品，寻找创建产品按钮
                    if i < len(products_batch):
                        print(f"🔍 进程 {process_id} 寻找创建产品按钮...")
                        if not erp.find_and_click_create_product_button():
                            print(f"⚠️ 进程 {process_id} 未找到创建产品按钮，尝试刷新页面...")
                            erp.driver.refresh()
                            time.sleep(5)
                            if not erp.find_and_click_create_product_button():
                                print(f"❌ 进程 {process_id} 刷新后仍未找到创建产品按钮")
                                break

                        print(f"✅ 进程 {process_id} 成功点击创建产品按钮，准备处理下一个产品")
                        time.sleep(2)  # 等待页面加载
                else:
                    failed_count += 1
                    print(f"❌ 进程 {process_id} 产品 {i} 处理失败")

                    # 记录失败
                    erp.daily_limit_manager.record_failure()

                    # 处理失败时，尝试返回主页面重新开始
                    print(f"🔄 进程 {process_id} 尝试返回主页面...")
                    try:
                        erp.driver.get("https://erp.sooxie.com/")
                        time.sleep(3)
                        if not erp.find_and_click_create_product_button():
                            print(f"❌ 进程 {process_id} 返回主页面后未找到创建产品按钮")
                            break
                    except:
                        print(f"❌ 进程 {process_id} 返回主页面失败")
                        break

            except Exception as e:
                failed_count += 1
                print(f"❌ 进程 {process_id} 处理产品 {i} 时出错: {e}")
                # 记录异常失败
                erp.daily_limit_manager.record_failure()
                continue

        print(f"📊 进程 {process_id} 批次处理完成: 成功 {success_count}, 失败 {failed_count}")

        return {
            "success_count": success_count,
            "failed_count": failed_count,
            "process_id": process_id
        }

    except Exception as e:
        print(f"❌ 进程 {process_id} 批次处理时出错: {e}")
        return {
            "success_count": success_count,
            "failed_count": len(products_batch) - success_count,
            "process_id": process_id
        }

    finally:
        # 最后关闭浏览器
        if erp:
            try:
                erp.close_browser()
                print(f"🔒 进程 {process_id} 浏览器已关闭")
            except:
                pass

def main_concurrent(num_processes=1, startup_interval=10):
    """
    并发处理主函数 - 处理所有工作表的产品

    Args:
        num_processes: 并发进程数，默认1个
        startup_interval: 进程启动间隔时间（秒），默认10秒
    """
    print(f"🚀 开始并发ERP自动化流程 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"🔧 并发进程数: {num_processes}")
    print(f"⏱️ 进程启动间隔: {startup_interval}秒")
    print("📊 将处理所有工作表的产品数据")

    # 读取所有工作表的产品数据
    product_data = ProductData()
    if not product_data.load_excel():
        print("❌ 读取Excel文件失败")
        return

    # 合并所有工作表的产品，并记录对应的类别路径
    all_products = []
    for sheet_name, products in product_data.products_by_sheet.items():
        # 从 CATEGORY_SHEET_MAPPING 获取类别路径
        category_path = None
        for config in CATEGORY_SHEET_MAPPING.values():
            if config['sheet_name'] == sheet_name:
                category_path = config['category_path']
                break
        
        if not category_path:
            print(f"⚠️ 警告：未找到工作表 '{sheet_name}' 对应的类别路径，跳过")
            continue
        
        # 为每个产品添加类别路径信息
        for product in products:
            product['_category_path'] = category_path
            product['_sheet_name'] = sheet_name
            all_products.append(product)
    
    if not all_products:
        print("❌ 没有找到产品数据")
        return
    
    print(f"📊 总共找到 {len(all_products)} 个产品，来自 {len(product_data.products_by_sheet)} 个工作表")


    # 检查每日创建限制
    print("\n📊 检查每日创建限制...")
    daily_limit_manager = DailyLimitManager()
    daily_limit_manager.print_daily_summary()

    if not daily_limit_manager.can_create_more():
        print("🚫 今日创建配额已用完，无法继续创建产品!")
        return

    remaining_quota = daily_limit_manager.get_remaining_quota()
    print(f"✅ 今日剩余配额: {remaining_quota} 个")

    # 如果待创建产品数量超过剩余配额，进行提醒
    if len(all_products) > remaining_quota:
        print(f"⚠️ 警告: 待创建产品数量({len(all_products)})超过今日剩余配额({remaining_quota})")
        print(f"📋 将只处理前 {remaining_quota} 个产品")
        all_products = all_products[:remaining_quota]

    # 共享配置
    shared_config = {
        'image_dir': './ready/',
        'excel_file': 'production.xlsx',
        'daily_limit': daily_limit_manager.daily_limit,
    }

    # 使用进程池并发处理
    success_count = 0
    failed_count = 0

    with ProcessPoolExecutor(max_workers=num_processes) as executor:
        # 提交所有任务，添加固定启动间隔避免并发冲突
        future_to_product = {}
        for i, product in enumerate(all_products, 1):
            # 在主线程中控制固定启动间隔，避免累加延迟
            if i > 1 and startup_interval > 0:
                print(f"⏳ 等待 {startup_interval} 秒后启动进程 {i}...")
                time.sleep(startup_interval)

            print(f"🚀 启动进程 {i} 处理产品: {product.get('产品标题', '')[:30]}...")

            future = executor.submit(process_single_product, product, i, shared_config, 0)  # 不需要在进程内部等待
            future_to_product[future] = (i, product)

        # 处理完成的任务
        for future in as_completed(future_to_product):
            product_index, product = future_to_product[future]
            try:
                success = future.result()
                if success:
                    success_count += 1
                    print(f"🎉 产品 {product_index} 处理完成")
                else:
                    failed_count += 1
                    print(f"💥 产品 {product_index} 处理失败")
            except Exception as e:
                failed_count += 1
                print(f"💥 产品 {product_index} 处理异常: {e}")

    # 输出最终统计
    total_count = success_count + failed_count
    print(f"\n📊 并发处理完成统计:")
    print(f"   ✅ 成功: {success_count}/{total_count}")
    print(f"   ❌ 失败: {failed_count}/{total_count}")
    print(f"   📈 成功率: {success_count/total_count*100:.1f}%" if total_count > 0 else "   📈 成功率: 0%")
    print("✅ 并发程序执行完成")

def main_concurrent_batch(num_processes=1, startup_interval=10):
    """
    批次并发处理主函数（保持浏览器打开）

    Args:
        num_processes: 并发进程数，默认1个
        startup_interval: 进程启动间隔时间（秒），默认10秒
    """
    print(f"🚀 开始批次并发ERP自动化流程 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"🔧 并发进程数: {num_processes}")
    print(f"⏱️ 进程启动间隔: {startup_interval}秒")
    print("📋 模式: 批次处理（保持浏览器打开）")
    print("📊 将处理所有工作表的产品数据")

    # 读取所有工作表的产品数据
    product_data = ProductData()
    if not product_data.load_excel():
        print("❌ 加载产品数据失败")
        return

    # 合并所有工作表的产品，并记录对应的类别路径
    all_products = []
    for sheet_name, products in product_data.products_by_sheet.items():
        # 从 CATEGORY_SHEET_MAPPING 获取类别路径
        category_path = None
        for config in CATEGORY_SHEET_MAPPING.values():
            if config['sheet_name'] == sheet_name:
                category_path = config['category_path']
                break
        
        if not category_path:
            print(f"⚠️ 警告：未找到工作表 '{sheet_name}' 对应的类别路径，跳过")
            continue
        
        # 为每个产品添加类别路径信息
        for product in products:
            product['_category_path'] = category_path
            product['_sheet_name'] = sheet_name
            all_products.append(product)
    
    if not all_products:
        print("✅ 没有需要处理的产品")
        return

    print(f"📦 总共找到 {len(all_products)} 个待处理产品，来自 {len(product_data.products_by_sheet)} 个工作表")

    # 检查每日创建限制
    print("\n📊 检查每日创建限制...")
    daily_limit_manager = DailyLimitManager()
    daily_limit_manager.print_daily_summary()

    if not daily_limit_manager.can_create_more():
        print("🚫 今日创建配额已用完，无法继续创建产品!")
        return

    remaining_quota = daily_limit_manager.get_remaining_quota()
    print(f"✅ 今日剩余配额: {remaining_quota} 个")

    # 如果待创建产品数量超过剩余配额，进行提醒
    if len(all_products) > remaining_quota:
        print(f"⚠️ 警告: 待创建产品数量({len(all_products)})超过今日剩余配额({remaining_quota})")
        print(f"📋 将只处理前 {remaining_quota} 个产品")
        all_products = all_products[:remaining_quota]

    # 将产品分配到不同的批次
    products_per_process = len(all_products) // num_processes
    remainder = len(all_products) % num_processes

    product_batches = []
    start_idx = 0

    for i in range(num_processes):
        # 为前面的进程分配额外的产品（如果有余数）
        batch_size = products_per_process + (1 if i < remainder else 0)
        end_idx = start_idx + batch_size

        if start_idx < len(all_products):
            batch = all_products[start_idx:end_idx]
            product_batches.append(batch)
            print(f"📋 进程 {i+1} 分配 {len(batch)} 个产品")

        start_idx = end_idx

    # 共享配置
    shared_config = {
        'image_dir': './ready/',
        'excel_file': 'production.xlsx',
        'daily_limit': daily_limit_manager.daily_limit,
    }

    # 使用进程池并发处理
    total_success = 0
    total_failed = 0

    with ProcessPoolExecutor(max_workers=num_processes) as executor:
        # 提交所有批次任务
        future_to_batch = {}
        for i, batch in enumerate(product_batches):
            if batch:  # 确保批次不为空
                # 在主线程中控制固定启动间隔，避免累加延迟
                if i > 0 and startup_interval > 0:
                    print(f"⏳ 等待 {startup_interval} 秒后启动进程 {i + 1}...")
                    time.sleep(startup_interval)

                print(f"🚀 启动进程 {i + 1} 处理 {len(batch)} 个产品...")

                future = executor.submit(
                    process_multiple_products_erp,
                    batch,
                    i + 1,
                    shared_config,
                    0  # 不需要在进程内部等待
                )
                future_to_batch[future] = (i + 1, len(batch))

        # 收集结果
        for future in as_completed(future_to_batch):
            process_id, batch_size = future_to_batch[future]
            try:
                result = future.result()
                success_count = result.get("success_count", 0)
                failed_count = result.get("failed_count", 0)

                total_success += success_count
                total_failed += failed_count

                print(f"✅ 进程 {process_id} 完成: 成功 {success_count}/{batch_size}")

            except Exception as e:
                total_failed += batch_size
                print(f"💥 进程 {process_id} 批次处理异常: {e}")

    # 输出最终统计
    total_count = total_success + total_failed
    print(f"\n📊 批次并发处理完成统计:")
    print(f"   ✅ 成功: {total_success}/{total_count}")
    print(f"   ❌ 失败: {total_failed}/{total_count}")
    print(f"   📈 成功率: {total_success/total_count*100:.1f}%" if total_count > 0 else "   📈 成功率: 0%")
    print("✅ 批次并发程序执行完成")

def test_modifications():
    """测试修改功能"""
    print("🧪 测试ERP自动化脚本修改...")
    print("=" * 50)

    # 测试1：并发参数解析
    print("📋 测试1：并发参数解析")
    test_cases = [
        ([], "单进程模式"),
        (["--concurrent"], "并发模式，默认1个进程，10秒间隔"),
        (["--concurrent", "3"], "并发模式，3个进程，10秒间隔"),
        (["--concurrent", "3", "15"], "并发模式，3个进程，15秒间隔"),
        (["--concurrent", "10"], "并发模式，10个进程，10秒间隔"),
        (["--concurrent", "3", "0"], "并发模式，3个进程，无启动间隔"),
        (["--concurrent", "invalid"], "并发模式，无效参数（使用默认值1个进程，10秒间隔）")
    ]

    for args, description in test_cases:
        print(f"   参数: {args if args else '无'} -> {description}")

        # 模拟参数解析
        if args and args[0] == "--concurrent":
            num_processes = 1
            startup_interval = 10

            if len(args) > 1:
                try:
                    num_processes = int(args[1])
                    num_processes = max(1, min(num_processes, 10))
                except ValueError:
                    num_processes = 1

            if len(args) > 2:
                try:
                    startup_interval = int(args[2])
                    startup_interval = max(0, min(startup_interval, 60))
                except ValueError:
                    startup_interval = 10

            print(f"      解析结果: {num_processes}个进程，{startup_interval}秒启动间隔")
        else:
            print(f"      解析结果: 单进程模式")

    # 测试2：图片选择逻辑说明
    print("\n📋 测试2：图片选择逻辑区分")
    print("   产品轮播图上传:")
    print("      1. 点击上传图片按钮")
    print("      2. 点击'选择空间图片'按钮")
    print("      3. 手动选择图片")
    print("      4. 点击确定")

    print("   外包装图片上传:")
    print("      1. 点击上传图片按钮")
    print("      2. 优先点击'使用产品图片'按钮")
    print("      3. 在弹窗中点击'全部选中'按钮")
    print("      4. 点击'确定'按钮")
    print("      5. 如果找不到'使用产品图片'，回退到原有逻辑")

    print("\n✅ 测试完成")
    print("=" * 50)

def test_shop_selection_only():
    """测试店铺选择功能"""
    print("🧪 开始测试店铺选择功能...")
    print("=" * 50)

    # 创建自动化实例
    erp = ERPAutomation(daily_limit=1, category_option=SELECTED_CATEGORY_OPTION)

    try:
        # 第一步：设置浏览器并登录
        print("\n=== 第一步：登录ERP系统 ===")
        if not erp.setup_browser():
            print("❌ 浏览器设置失败，测试退出")
            return False

        if not erp.login_erp():
            print("❌ 登录失败，测试退出")
            return False

        # 第二步：处理登录后的弹窗
        print("\n=== 第二步：处理登录后弹窗 ===")
        erp.handle_popups()

        # 第三步：点击创建产品按钮
        print("\n=== 第三步：打开创建产品弹窗 ===")
        if not erp.click_create_product():
            print("❌ 无法打开创建产品弹窗，测试退出")
            return False

        # 第四步：先测试产品类别选择（避免后续被重置）
        print("\n=== 第四步：测试产品类别选择 ===")
        if erp.fill_product_category():
            print("✅ 产品类别选择测试成功！")

            # 第五步：再测试店铺选择（避免被产品类别重置）
            print("\n=== 第五步：测试店铺选择 ===")
            if erp.select_shop("Shumeng shoes and clothing"):
                print("✅ 店铺选择测试成功！")
                result = True
            else:
                print("❌ 店铺选择测试失败！")
                result = False
        else:
            print("❌ 产品类别选择测试失败！")
            result = False

        # 等待一下让用户看到结果
        print("\n⏳ 等待5秒让您查看结果...")
        time.sleep(5)

        return result

    except Exception as e:
        print(f"❌ 测试过程出错: {e}")
        return False

    finally:
        try:
            erp.close_browser()
        except:
            pass
        print("✅ 测试完成")


def parse_cli_args(argv):
    """解析通用命令行参数，返回每日限制和剩余参数"""
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--limit", type=str, help="每日创建限制（1-500）")

    try:
        args, remaining = parser.parse_known_args(argv[1:])
    except SystemExit:
        # 捕获非法参数格式，保持脚本继续运行
        print("⚠️ 命令行参数解析失败，使用默认配置")
        return 200, argv[1:]

    daily_limit = 200
    if args.limit is not None:
        try:
            parsed_limit = int(args.limit)
            if parsed_limit < 1 or parsed_limit > 500:
                print("⚠️ 每日限制需在1-500之间，自动裁剪到合法范围")
            daily_limit = max(1, min(parsed_limit, 500))
        except ValueError:
            print("⚠️ 无效的每日限制数值，使用默认值200")
        else:
            print(f"📊 设置每日创建限制: {daily_limit} 个")

    print("📊 将处理所有工作表的产品数据")

    return daily_limit, remaining


if __name__ == "__main__":
    # 选择运行模式
    import sys

    daily_limit, remaining_args = parse_cli_args(sys.argv)

    # 剩余参数用于选择运行模式
    main_args = remaining_args

    if main_args and main_args[0] == "--help":
        # 帮助信息
        print("🤖 ERP自动化脚本使用说明")
        print("=" * 50)
        print("使用方法:")
        print("  python erp_automation.py                    # 单进程模式")
        print("  python erp_automation.py --concurrent 2     # 并发模式，2个进程")
        print("  python erp_automation.py --batch 2          # 批次模式，2个进程（推荐）")
        print("  python erp_automation.py --test             # 测试模式")
        print("")
        print("模式说明:")
        print("  单进程模式: 逐个处理产品，稳定但较慢")
        print("  并发模式:   每个进程处理一个产品，每次都重新打开浏览器")
        print("  批次模式:   保持浏览器打开，连续处理多个产品（效率最高）")
        print("")
        print("参数说明:")
        print("  --concurrent [进程数] [启动间隔]")
        print("  --batch [进程数] [启动间隔]")
        print("  --limit [每日限制数量]")
        print("  进程数: 1-10 (并发模式) 或 1-10 (批次模式)")
        print("  启动间隔: 0-60秒，默认10秒")
        print("  每日限制: 1-500，默认200")
        print("")
        print("📊 程序将自动读取并处理 Excel 中所有工作表的产品数据")
        print("工作表到类别的映射关系:")
        for option_key, config in CATEGORY_SHEET_MAPPING.items():
            print(f"  {config['sheet_name']} -> {config['category_path']}")
        print("")
        print("每日限制功能:")
        print("  脚本会自动记录每天创建成功的产品数量")
        print("  达到每日限制后会自动停止创建")
        print("  每天0点自动重置计数")
        print("  统计数据保存在 daily_stats.json 文件中")
        print("")
        print("示例:")
        print("  python erp_automation.py --batch 2 5        # 2个进程，5秒启动间隔")
        print("  python erp_automation.py --concurrent 3     # 3个进程，默认10秒间隔")
        print("  python erp_automation.py --limit 150        # 设置每日限制为150个")
        print("  python erp_automation.py --batch 2 --limit 100  # 2个进程，每日限制100个")
    elif main_args and main_args[0] == "--test":
        # 测试模式
        test_modifications()
    elif main_args and main_args[0] == "--test-shop":
        # 测试店铺选择功能
        test_shop_selection_only()
    elif main_args and main_args[0] == "--concurrent":
        # 并发模式（每个进程处理一个产品）
        num_processes = 1  # 默认改为1
        startup_interval = 10  # 默认启动间隔10秒

        if len(main_args) > 1:
            try:
                num_processes = int(main_args[1])
                num_processes = max(1, min(num_processes, 10))  # 限制在1-10之间
            except ValueError:
                print("⚠️ 无效的进程数，使用默认值1")

        if len(main_args) > 2:
            try:
                startup_interval = int(main_args[2])
                startup_interval = max(0, min(startup_interval, 60))  # 限制在0-60秒之间
            except ValueError:
                print("⚠️ 无效的启动间隔时间，使用默认值10秒")

        print(f"🔄 启动并发模式，进程数: {num_processes}，启动间隔: {startup_interval}秒")
        main_concurrent(num_processes, startup_interval)
    elif main_args and main_args[0] == "--batch":
        # 批次并发模式（保持浏览器打开）
        num_processes = 1  # 默认改为1
        startup_interval = 10  # 默认启动间隔10秒

        if len(main_args) > 1:
            try:
                num_processes = int(main_args[1])
                num_processes = max(1, min(num_processes, 10))  # 批次模式限制在1-10之间
            except ValueError:
                print("⚠️ 无效的进程数，使用默认值1")

        if len(main_args) > 2:
            try:
                startup_interval = int(main_args[2])
                startup_interval = max(0, min(startup_interval, 60))  # 限制在0-60秒之间
            except ValueError:
                print("⚠️ 无效的启动间隔时间，使用默认值10秒")

        print(f"🔄 启动批次并发模式，进程数: {num_processes}，启动间隔: {startup_interval}秒")
        print("📋 注意: 批次模式会保持浏览器打开，连续处理多个产品")
        main_concurrent_batch(num_processes, startup_interval)
    else:
        # 单进程模式
        print("🔄 启动单进程模式")
        main(daily_limit)

    # 如果想单独测试功能，可以取消下面的注释
    # test_sku_category_batch_modify_only()
    # test_preview_image_menu_only()
    # test_size_chart_only()
